Elasticsearch:Node.js ECS 日志记录 - Morgan
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
const winston = require('winston');
const { format } = require('logform');
const { ElasticsearchTransport } = require('winston-elasticsearch');
// 定义Elasticsearch日志格式
const ecsFormat = format(info => {
// 添加ECS兼容的日志格式
info.ecs = {
version: '1.4.0'
};
info.log = {
level: info.level,
original: info.message
};
return info;
});
// 创建Elasticsearch传输实例
const elasticsearchTransport = new ElasticsearchTransport({
indexPrefix: 'app-logs',
// 其他Elasticsearch相关配置
});
// 创建winston日志实例
const logger = winston.createLogger({
level: 'info',
format: format.combine(
ecsFormat(),
format.json()
),
transports: [
elasticsearchTransport
]
});
// 使用logger记录日志
logger.info('这是一条info级别的日志信息');
这段代码首先引入了必要的模块,定义了一个兼容Elastic Common Schema (ECS) 的日志格式,然后创建了一个Elasticsearch传输实例,并将其作为日志传输方式添加到winston日志系统中。最后,通过调用logger的info方法来记录日志信息。这样,所有通过logger记录的日志都会自动格式化为ECS兼容的格式,并发送到Elasticsearch进行存储和查询。
评论已关闭