fullstack-build / tslog

📝 tslog - Universal Logger for TypeScript and JavaScript
https://tslog.js.org
MIT License
1.35k stars 63 forks source link

Format pretty and json log entries #236

Open mousseq opened 1 year ago

mousseq commented 1 year ago

I would like to customize the pretty format and the json format in ways not currently supported.

  1. I cannot create a pretty format that is json as I cannot obtain the message text. That is, in an ordinary log message (not one invoked with an Error object), the message text is not available for formatting. Consequently, I cannot create a log entry that contains the the message text in json format. For example:
    
    const foptions = {
    "timestamp":"{{dateIsoStr}}",
    "level":"{{logLevelName}}",
    "location":"{{filePathWithLine}}",
    "message": "{{message}}"
    };
    const pretty_log = JSON.stringify( foptions );

const options = { name: "pretty", type: "pretty", prettyLogTemplate: pretty_log, stylePrettyLogs: false };

const plogger = new Logger( options );


2. I would like to produce json log entries that do not include the _meta element or include only selected properties of the _meta element. It would be helpful if I could specify a format for the json output that includes only the fields that I want. This could be achieved by specifying the fields that I want or specifying the fields that I don't want.
For example:
```javascript
const json_options = {
    "include": [ "name", "message", "stack", "date", "logLevelName" ],
    "stack include" : [ "fullFilePath", "method" ]
};

const json_log = JSON.stringify( json_options );

const options = {
    name: "json",
    type: "json",
    jsonLogTemplate: json_log
};
const jlogger = new Logger( options );
jjm340 commented 8 months ago

There's a workaround for this, but it's ugly: You can create a subclass:

class CustomLogger extends BaseLogger<LoggerPayload> {
  constructor(
    settings?: ISettingsParam<LoggerPayload>,
    logObj?: LoggerPayload,
  ) {
    super(settings, logObj, 5);
  }

  override log(logLevelId: number, logLevelName: string, ...args: unknown[]) {
    return {
      logLevelId,
      logLevelName,
      ...args,
    } as any;
  }

Return the payload as any and it will get rid of the meta fields and only return what you decide to return in this function.

jjm340 commented 8 months ago

Nevermind, this just breaks the logger!