如果检查日志“级别”的条件不起作用

问题描述 投票:0回答:1

我已经设置了一个基本的 Node.js 应用程序,并且正在使用 Winston 包将日志发送到 Logstash。我没有使用 filebeat。在弹性云部署中,我想将日志保存在单独的索引中,为此我尝试过滤数据并根据其“级别”(信息、错误)分配索引。但是Logstash配置文件中的if else条件总是转到else条件并将数据记录到else条件中提到的索引中。检查“消息”是否是对象的第一个 if 条件工作正常,但第二个条件总是转到 else。

Logstash 配置文件

input {
    tcp {
        port => 6000
    }
}

filter {
    if [message] =~ /^{.*}$/ {
        if [level] == 'info' {
            mutate {
                add_field => { "index" => "error-logs-%{+YYYY.MM.dd}" }
            }
        } else {
            mutate {
                add_field => { "index" => "api-logs-%{+YYYY.MM.dd}" }
            }
        }
    } else {
        drop {}
    }
}

output {
    elasticsearch { 
        cloud_id => "cloud_id" 
        cloud_auth => "credentials for cloud"
        index => "%{index}"
    }
    stdout { codec => rubydebug }
}

Node.js 应用程序文件

const express = require('express');
const winston = require('winston');
const {ecsFormat} = require('@elastic/ecs-winston-format');
const {ElasticsearchTransport} = require('winston-elasticsearch');
const transports = require('winston-logstash');
const app = express();
app.use(express.json());

const api_logger = winston.createLogger({
    format: winston.format.json(),
    transports: [
        new ElasticsearchTransport({
            clientOpts: {node: 'http://localhost:6000'},
        })
    ]
});

const error_logger = winston.createLogger({
    format: winston.format.json(),
    transports: [
        new ElasticsearchTransport({
            clientOpts: {node: 'http://localhost:6000'},
        })
    ]
})

const signup = async function (req, res) {
    try {
        const { firstName, lastName, phoneNumber, emailId, password } = req.body;
        res.status(200).json({message: "Request successful!"});
        if (req.body) {api_logger.info('api-logs',{
                messsage: 'New signup request', 
                request_header: req.headers,
                request_body: req.body
            })
        }
    } catch (error) {
        console.log(error);
        error_logger.error(`Error,${error.message}`, {request_header : req.headers, request_body : req.body});
        res.status(500).json({ message: error.message });
    }
};

app.post("/new", signup);

app.listen(7000, console.log("Server is running on port 7000!"))
node.js elasticsearch logstash elastic-stack logstash-configuration
1个回答
0
投票

您可以使用 @elastic/ecs-winston-format 而不是使用winston.format.json()。它与 ECS(弹性通用架构)兼容。

Npmjs 链接

© www.soinside.com 2019 - 2024. All rights reserved.