Logging is a critical aspect of software development and maintenance. Proper logging helps developers and tech leads understand the state of an application, diagnose issues, and ensure smooth operation. Logging levels provide a mechanism to categorize the importance and nature of the log messages generated by an application. This article delves into the different logging levels, their appropriate usage, and provides examples in Node.js and Spring Boot Java.
The common logging levels, in increasing order of severity, include:
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
Here’s a sample configuration for logging in a Spring Boot application:
<?xml version="1.0" encoding="UTF-8"?><configuration><!-- JSON Console Appender --><appender name="JSON_LOG" class="ch.qos.logback.core.ConsoleAppender"><layout class="ch.qos.logback.contrib.json.classic.JsonLayout"><jsonFormatter class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter"><prettyPrint>false</prettyPrint></jsonFormatter><timestampFormat>yyyy-MM-dd' 'HH:mm:ss.SSS</timestampFormat><appendLineSeparator>true</appendLineSeparator></layout></appender><!-- Standard Console Appender --><appender name="STANDARD_LOG" class="ch.qos.logback.core.ConsoleAppender"><layout class="ch.qos.logback.classic.PatternLayout"><Pattern>%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Pattern></layout></appender><!-- Logging Configuration for 'local', 'dev', and 'test' profiles --><springProfile name="local | dev | test"><root level="INFO"><appender-ref ref="STANDARD_LOG"/></root></springProfile><!-- Logging Configuration for 'prod' profile --><springProfile name="prod"><root level="INFO"><appender-ref ref="JSON_LOG"/></root></springProfile></configuration>
Here’s a sample configuration for logging in a Node.js application using the winston
library with ESM syntax:
import { createLogger, format, transports } from 'winston';const { combine, timestamp, json, printf, colorize, simple } = format;// Custom log formatconst logFormat = printf(({ level, message, timestamp }) => {return `${timestamp} ${level}: ${message}`;});// Logger configurationconst logger = createLogger({level: 'info',format: combine(timestamp({format: 'YYYY-MM-DD HH:mm:ss'}),json()),transports: [new transports.Console({format: combine(timestamp(),logFormat)}),new transports.File({ filename: 'error.log', level: 'error' }),new transports.File({ filename: 'combined.log' })],});// Development environment loggingif (process.env.NODE_ENV !== 'production') {logger.add(new transports.Console({format: combine(colorize(),simple())}));}export default logger;