在Linux系统中,JavaScript日志格式通常遵循以下几种常见的格式:
JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。
{
"timestamp": "2023-04-10T12:34:56Z",
"level": "INFO",
"message": "User logged in successfully",
"userId": "12345",
"ipAddress": "192.168.1.1"
}
CSV(Comma-Separated Values)是一种简单的文本格式,用于存储表格数据。
timestamp,level,message,userId,ipAddress
2023-04-10T12:34:56Z,INFO,User logged in successfully,12345,192.168.1.1
你可以根据需要自定义日志格式,例如:
[2023-04-10T12:34:56Z] [INFO] User logged in successfully - userId: 12345, ipAddress: 192.168.1.1
许多JavaScript日志库(如winston
、log4js
)提供了多种日志格式选项。例如,使用winston
:
const winston = require('winston');
const logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.printf(({ timestamp, level, message, userId, ipAddress }) => {
return `[${timestamp}] [${level}] ${message} - userId: ${userId}, ipAddress: ${ipAddress}`;
})
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' })
]
});
logger.info('User logged in successfully', { userId: '12345', ipAddress: '192.168.1.1' });
结构化日志通常以键值对的形式存储,便于后续的数据分析和处理。
{
"event": "user_login",
"timestamp": "2023-04-10T12:34:56Z",
"level": "INFO",
"userId": "12345",
"ipAddress": "192.168.1.1"
}
选择哪种日志格式取决于你的具体需求和应用场景。JSON和CSV格式便于数据解析和处理,而自定义文本格式和结构化日志则提供了更大的灵活性。使用日志库可以简化日志记录和管理的过程。