1
0
mirror of https://github.com/xuthus83/pigallery2.git synced 2025-01-14 14:43:17 +08: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 {SupportedFormats} from '../../common/SupportedFormats';
import {ServerTime} from './ServerTimingMWs'; import {ServerTime} from './ServerTimingMWs';
import {SortByTypes} from '../../common/entities/SortingMethods'; import {SortByTypes} from '../../common/entities/SortingMethods';
import {Logger} from '../Logger';
export class GalleryMWs { export class GalleryMWs {
@ServerTime('1.db', 'List Directory') @ServerTime('1.db', 'List Directory')
@ -109,7 +110,7 @@ export class GalleryMWs {
}); });
res.on('close', () => { res.on('close', () => {
console.log('zip ' + archive.pointer() + ' bytes'); Logger.info('zip ' + archive.pointer() + ' bytes');
}); });
archive.on('error', (err: Error) => { archive.on('error', (err: Error) => {

View File

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

View File

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

View File

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

View File

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

View File

@ -3,7 +3,7 @@ import {PrivateConfigClass} from '../../../common/config/private/PrivateConfigCl
import {ConfigClassBuilder} from 'typeconfig/node'; import {ConfigClassBuilder} from 'typeconfig/node';
import {ExtensionConfigTemplateLoader} from './ExtensionConfigTemplateLoader'; import {ExtensionConfigTemplateLoader} from './ExtensionConfigTemplateLoader';
import {NotificationManager} from '../NotifocationManager'; import {NotificationManager} from '../NotifocationManager';
import {Logger} from '../../Logger';
const LOG_TAG = '[ExtensionConfigWrapper]'; 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 await pc.load(); // loading the basic configs, but we do not know the extension config hierarchy yet
} catch (e) { } catch (e) {
console.error(LOG_TAG, 'Error during loading config. Reverting to defaults.'); Logger.error(LOG_TAG, 'Error during loading config. Reverting to defaults.\n', e);
console.error(e);
if (showDetailedError) { 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))); 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 pc.loadSync(); // loading the basic configs, but we do not know the extension config hierarchy yet
} catch (e) { } catch (e) {
console.error(LOG_TAG, 'Error during loading config. Reverting to defaults.'); Logger.error(LOG_TAG, 'Error during loading config. Reverting to defaults.\n', e);
console.error(e);
if (showDetailedError) { 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))); 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), 'Unknown directory reading error, skipping: ' + path.join(relativeDirectoryName, file),
err.toString() err.toString()
); );
console.error(err); Logger.error(err);
} }
} else if (PhotoProcessing.isPhoto(fullFilePath)) { } else if (PhotoProcessing.isPhoto(fullFilePath)) {
try { try {
@ -218,7 +218,7 @@ export class DiskManager {
', reason: ' + ', reason: ' +
err.toString() err.toString()
); );
console.error(err); Logger.error(err);
} }
} else if (VideoProcessing.isVideo(fullFilePath)) { } else if (VideoProcessing.isVideo(fullFilePath)) {
try { try {

View File

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

View File

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

View File

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

View File

@ -93,8 +93,7 @@ export class IndexingJob<
} catch (e) { } catch (e) {
this.Progress.log('Skipping. Indexing failed for: ' + directory); this.Progress.log('Skipping. Indexing failed for: ' + directory);
this.Progress.Skipped++; this.Progress.Skipped++;
Logger.warn(LOG_TAG, 'Skipping. Indexing failed for: ' + directory); Logger.warn(LOG_TAG, 'Skipping. Indexing failed for: ' + directory, + '\n', e);
console.error(e);
} }
if (this.Progress.State !== JobProgressStates.running) { if (this.Progress.State !== JobProgressStates.running) {
return false; 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 => { const pr = new Promise<void>((resolve): void => {
this.prResolve = resolve; this.prResolve = resolve;
}); });
this.init().catch(console.error); this.init().catch(Logger.error);
this.run(); this.run();
if (!this.IsInstant) { if (!this.IsInstant) {
// if instant, wait for execution, otherwise, return right away // if instant, wait for execution, otherwise, return right away

View File

@ -1,6 +1,7 @@
import {MediaDTOWithThPath, Messenger} from './Messenger'; import {MediaDTOWithThPath, Messenger} from './Messenger';
import {DynamicConfig} from '../../../common/entities/DynamicConfig'; import {DynamicConfig} from '../../../common/entities/DynamicConfig';
import {DefaultMessengers} from '../../../common/entities/job/JobDTO'; import {DefaultMessengers} from '../../../common/entities/job/JobDTO';
import { Logger } from '../../Logger';
export class StdoutMessenger extends Messenger { export class StdoutMessenger extends Messenger {
public readonly Name = DefaultMessengers[DefaultMessengers.Stdout]; public readonly Name = DefaultMessengers[DefaultMessengers.Stdout];
@ -12,6 +13,6 @@ export class StdoutMessenger extends Messenger {
protected async sendMedia(config: never, media: MediaDTOWithThPath[]) { 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 // Flush out the stack to the console
Logger.error('Unexpected error:'); Logger.error('Unexpected error:\n', err);
console.error(err);
return next( return next(
new ErrorDTO( new ErrorDTO(
ErrorCodes.SERVER_ERROR, ErrorCodes.SERVER_ERROR,

View File

@ -51,7 +51,7 @@ export class Server {
'Running in DEBUG mode, set env variable NODE_ENV=production to disable ' '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 { get Server(): HttpServer {