# Custom layout

You can add your own layouts with Layout() before pushing a configure to your logger.

// customLayout.ts
import {BaseLayout, LogEvent, Layout} from "@tsed/logger";
import {formatLogData} from "ts-log-debug/lib/utils/inpectUtils";

@Layout({name: "customJson"})
export class JsonLayout extends BaseLayout {
  transform(loggingEvent: LogEvent, timezoneOffset?): string {
    const log = {
      startTime: loggingEvent.startTime,
      categoryName: loggingEvent.categoryName,
      level: loggingEvent.level.toString(),
      data: loggingEvent.data,
      context: loggingEvent.context
    };

    log.data = log.data.map((data) => formatLogData([data]));

    return JSON.stringify(log) + (this.config["separator"] || "");
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

This layout can be use like this:

import {Logger} from "@tsed/logger";
import "./customLayout.ts";

const logger = new Logger("loggerName");

logger.appenders.set("std-log", {
  type: "console",
  layout: {type: "customJson"},
  level: ["debug", "info", "trace"]
});
logger.info("this is just a test");
logger.error("of a custom appender");
logger.warn("that outputs json");
1
2
3
4
5
6
7
8
9
10
11
12
13

This example outputs the following:

{"startTime":"2017-06-05T22:23:08.479Z","categoryName":"json-test","data":["this is just a test"],"level":"INFO","context":{}},
{"startTime":"2017-06-05T22:23:08.483Z","categoryName":"json-test","data":["of a custom appender"],"level":"ERROR","context":{}},
{"startTime":"2017-06-05T22:23:08.483Z","categoryName":"json-test","data":["that outputs json"],"level""WARN","context":{}},
1
2
3

Last Updated: 10/26/2023, 6:30:07 AM

Other topics