1
0
mirror of https://github.com/bpatrik/pigallery2.git synced 2025-01-08 04:03:48 +02:00

Always use Logger class and try to log once per event

This unifies logging across the backend to always use the Logger class,
always only logs to stdout (rather than an inconsistent mix of stdout
and stderr, depending on whether console.error was used), and removes
logging where two log events happened for the same message

For example, this pattern:

```js
Logger.error("Whoops, something went wrong:")
console.error(err)
```

That causes two separate log events, and depending on the log transport
used, could cause relevant log messages to get split across multiple
events and therefore be harder (usually just more tedious) to connect
and debug in production environments.
This commit is contained in:
sarayourfriend 2024-03-29 17:45:08 +11:00
parent 3be8f1b194
commit ba6e7c03ec
No known key found for this signature in database
15 changed files with 32 additions and 33 deletions

View File

@ -17,6 +17,7 @@ import {LocationLookupException} from '../exceptions/LocationLookupException';
import {SupportedFormats} from '../../common/SupportedFormats';
import {ServerTime} from './ServerTimingMWs';
import {SortByTypes} from '../../common/entities/SortingMethods';
import {Logger} from '../Logger';
export class GalleryMWs {
@ServerTime('1.db', 'List Directory')
@ -109,7 +110,7 @@ export class GalleryMWs {
});
res.on('close', () => {
console.log('zip ' + archive.pointer() + ' bytes');
Logger.info('zip ' + archive.pointer() + ' bytes');
});
archive.on('error', (err: Error) => {

View File

@ -132,11 +132,14 @@ export class RenderingMWs {
): void {
if (err instanceof ErrorDTO) {
if (err.details) {
const logFn = Logger.logLevelForError(err.code)
logFn('Handled error:');
LoggerRouter.log(logFn, req, res);
// use separate rendering for detailsStr
const d = err.detailsStr;
delete err.detailsStr;
console.log(err);
logFn(err);
err.detailsStr = d;
delete err.details; // do not send back error object to the client side

View File

@ -123,7 +123,7 @@ export class GalleryManager {
);
ObjectManagers.getInstance()
.IndexingManager.indexDirectory(relativeDirectoryName)
.catch(console.error);
.catch(Logger.error);
}
return await this.getParentDirFromId(connection, dir.id);
}

View File

@ -100,13 +100,13 @@ export class IndexingManager {
resolve(dirClone);
// save directory to DB
this.queueForSave(scannedDirectory).catch(console.error);
this.queueForSave(scannedDirectory).catch(Logger.error);
} catch (error) {
NotificationManager.warning(
'Unknown indexing error for: ' + relativeDirectoryName,
error.toString()
);
console.error(error);
Logger.error(error);
return reject(error);
}
});

View File

@ -155,8 +155,7 @@ export class SQLConnection {
this.connection = null;
}
} catch (err) {
console.error('Error during closing sql db:');
console.error(err);
Logger.error('Error during closing sql db:\n', err);
}
}

View File

@ -3,7 +3,7 @@ import {PrivateConfigClass} from '../../../common/config/private/PrivateConfigCl
import {ConfigClassBuilder} from 'typeconfig/node';
import {ExtensionConfigTemplateLoader} from './ExtensionConfigTemplateLoader';
import {NotificationManager} from '../NotifocationManager';
import {Logger} from '../../Logger';
const LOG_TAG = '[ExtensionConfigWrapper]';
@ -19,10 +19,9 @@ export class ExtensionConfigWrapper {
await pc.load(); // loading the basic configs, but we do not know the extension config hierarchy yet
} catch (e) {
console.error(LOG_TAG, 'Error during loading config. Reverting to defaults.');
console.error(e);
Logger.error(LOG_TAG, 'Error during loading config. Reverting to defaults.\n', e);
if (showDetailedError) {
console.error(LOG_TAG, 'This is most likely due to: 1) you added a bad configuration in the server.json OR 2) The configuration changed in the latest release.');
Logger.error(LOG_TAG, 'This is most likely due to: 1) you added a bad configuration in the server.json OR 2) The configuration changed in the latest release.');
NotificationManager.error('Can\'t load config. Reverting to default. This is most likely due to: 1) you added a bad configuration in the server.json OR 2) The configuration changed in the latest release.', (e.toString ? e.toString() : JSON.stringify(e)));
}
}
@ -37,10 +36,9 @@ export class ExtensionConfigWrapper {
pc.loadSync(); // loading the basic configs, but we do not know the extension config hierarchy yet
} catch (e) {
console.error(LOG_TAG, 'Error during loading config. Reverting to defaults.');
console.error(e);
Logger.error(LOG_TAG, 'Error during loading config. Reverting to defaults.\n', e);
if (showDetailedError) {
console.error(LOG_TAG, 'This is most likely due to: 1) you added a bad configuration in the server.json OR 2) The configuration changed in the latest release.');
Logger.error(LOG_TAG, 'This is most likely due to: 1) you added a bad configuration in the server.json OR 2) The configuration changed in the latest release.');
NotificationManager.error('Ca\'nt load config. Reverting to default. This is most likely due to: 1) you added a bad configuration in the server.json OR 2) The configuration changed in the latest release.', (e.toString ? e.toString() : JSON.stringify(e)));
}
}

View File

@ -179,7 +179,7 @@ export class DiskManager {
'Unknown directory reading error, skipping: ' + path.join(relativeDirectoryName, file),
err.toString()
);
console.error(err);
Logger.error(err);
}
} else if (PhotoProcessing.isPhoto(fullFilePath)) {
try {
@ -218,7 +218,7 @@ export class DiskManager {
', reason: ' +
err.toString()
);
console.error(err);
Logger.error(err);
}
} else if (VideoProcessing.isVideo(fullFilePath)) {
try {

View File

@ -41,7 +41,7 @@ export class MetadataLoader {
metadata.fileSize = stat.size;
metadata.creationDate = stat.mtime.getTime(); //Default date is file system time of last modification
} catch (err) {
console.log(err);
Logger.info(err);
// ignoring errors
}
try {
@ -214,8 +214,7 @@ export class MetadataLoader {
try {
await fileHandle.read(data, 0, bufferSize, 0);
} catch (err) {
Logger.error(LOG_TAG, 'Error during reading photo: ' + fullPath);
console.error(err);
Logger.error(LOG_TAG, 'Error during reading photo: ' + fullPath + '\n', err);
return MetadataLoader.EMPTY_METADATA;
} finally {
await fileHandle.close();
@ -295,13 +294,11 @@ export class MetadataLoader {
metadata.creationDate = 0;
}
} catch (err) {
Logger.error(LOG_TAG, 'Error during reading photo: ' + fullPath);
console.error(err);
Logger.error(LOG_TAG, 'Error during reading photo: ' + fullPath + '\n', err);
return MetadataLoader.EMPTY_METADATA;
}
} catch (err) {
Logger.error(LOG_TAG, 'Error during reading photo: ' + fullPath);
console.error(err);
Logger.error(LOG_TAG, 'Error during reading photo: ' + fullPath + '\n', err);
return MetadataLoader.EMPTY_METADATA;
}
return metadata;

View File

@ -1,5 +1,6 @@
import {TaskQue} from './TaskQue';
import {EventLoopHandler} from '../EventLoopHandler';
import { Logger } from '../../Logger';
export interface ITaskExecuter<I, O> {
execute(input: I): Promise<O>;
@ -30,7 +31,7 @@ export class TaskExecuter<I, O> implements ITaskExecuter<I, O> {
execute(input: I): Promise<O> {
const promise = this.taskQue.add(input).promise.obj;
this.run().catch(console.error);
this.run().catch(Logger.error);
return promise;
}
}

View File

@ -3,6 +3,7 @@ import * as path from 'path';
import {ProjectPath} from '../../ProjectPath';
import {Config} from '../../../common/config/private/Config';
import {JobProgressDTO, JobProgressStates,} from '../../../common/entities/job/JobProgressDTO';
import { Logger } from '../../Logger';
export class JobProgressManager {
private static readonly VERSION = 3;
@ -20,7 +21,7 @@ export class JobProgressManager {
constructor() {
this.dbPath = path.join(ProjectPath.DBFolder, 'jobs.db');
this.loadDB().catch(console.error);
this.loadDB().catch(Logger.error);
}
get Progresses(): { [key: string]: JobProgressDTO } {
@ -89,7 +90,7 @@ export class JobProgressManager {
return;
}
this.timer = setTimeout(async (): Promise<void> => {
this.saveDB().catch(console.error);
this.saveDB().catch(Logger.error);
this.timer = null;
}, 5000);
}

View File

@ -93,8 +93,7 @@ export class IndexingJob<
} catch (e) {
this.Progress.log('Skipping. Indexing failed for: ' + directory);
this.Progress.Skipped++;
Logger.warn(LOG_TAG, 'Skipping. Indexing failed for: ' + directory);
console.error(e);
Logger.warn(LOG_TAG, 'Skipping. Indexing failed for: ' + directory, + '\n', e);
}
if (this.Progress.State !== JobProgressStates.running) {
return false;

View File

@ -71,7 +71,7 @@ export abstract class Job<T extends Record<string, unknown> = Record<string, unk
const pr = new Promise<void>((resolve): void => {
this.prResolve = resolve;
});
this.init().catch(console.error);
this.init().catch(Logger.error);
this.run();
if (!this.IsInstant) {
// if instant, wait for execution, otherwise, return right away

View File

@ -1,6 +1,7 @@
import {MediaDTOWithThPath, Messenger} from './Messenger';
import {DynamicConfig} from '../../../common/entities/DynamicConfig';
import {DefaultMessengers} from '../../../common/entities/job/JobDTO';
import { Logger } from '../../Logger';
export class StdoutMessenger extends Messenger {
public readonly Name = DefaultMessengers[DefaultMessengers.Stdout];
@ -12,6 +13,6 @@ export class StdoutMessenger extends Messenger {
protected async sendMedia(config: never, media: MediaDTOWithThPath[]) {
console.log(media.map(m => m.thumbnailPath));
Logger.info(media.map(m => m.thumbnailPath));
}
}

View File

@ -38,8 +38,7 @@ export class ErrorRouter {
}
// Flush out the stack to the console
Logger.error('Unexpected error:');
console.error(err);
Logger.error('Unexpected error:\n', err);
return next(
new ErrorDTO(
ErrorCodes.SERVER_ERROR,

View File

@ -51,7 +51,7 @@ export class Server {
'Running in DEBUG mode, set env variable NODE_ENV=production to disable '
);
}
this.init(listen).catch(console.error);
this.init(listen).catch(Logger.error);
}
get Server(): HttpServer {