diff --git a/src/index.ts b/src/index.ts index 8b735b8..7b31798 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,6 +6,18 @@ export const levels = winston.config.npm.levels; export type Logger = winston.Logger; +/* A custom format that is used to format the error object. */ +const formatError = winston.format(info => { + if ("error" in info && info.error instanceof Error) { + const { + error: { message, stack, ...rest } + } = info; + info.error = { message, stack, ...rest }; + } + + return info; +}); + export const createLogger = ( { logLevel = "info", @@ -32,8 +44,17 @@ export const createLogger = ( // moves all the other fields in the message to `metadata` property metadata({ - fillExcept: ["message", "level", "timestamp", "service", "type"] + fillExcept: [ + "message", + "level", + "timestamp", + "service", + "type", + "error" + ] }), + // custom formatter to format the "error" property + formatError(), // default log format is JSON json() diff --git a/test/index.test.js b/test/index.test.js index 5842960..2b6ad08 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -2,4 +2,10 @@ const { createLogger } = require("logger-safe-security"); const logger = createLogger({ service: "sample" }); logger.info("This is a sample logger"); -logger.info("This is a sample logger with more information", { planet: "Earth" }); \ No newline at end of file +logger.info("This is a sample logger with more information", { + planet: "Earth", +}); + +/* Logging the error property. */ +const err = new Error("This is a sample Error"); +logger.info("Error occurred while performing the operation", { error: err }); diff --git a/test/index.test.ts b/test/index.test.ts index 035c22e..fab2e72 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -2,4 +2,9 @@ import { createLogger } from "logger-safe-security"; const logger = createLogger({ service: "sample" }); logger.info("This is a sample logger"); -logger.info("This is a sample logger with more information", { planet: "Earth" }); \ No newline at end of file +logger.info("This is a sample logger with more information", { planet: "Earth" }); + + +/* Logging the error property. */ +const err = new Error("This is a sample Error"); +logger.info("Error occurred while performing the operation", { error: err });