如何删除日志信息本身之前的附加信息?



我使用Apache Log4j logger (import org.apache.logging.log4j.core.Logger),以便以JSON格式向syslog服务器发送消息。

我发送的消息是这样的:

{"id":"1"}

然而,在syslog服务器中我收到:
Feb 14 10:33:27 localhost{"id"1"}

如何在消息本身之前删除这个额外的信息,(Feb 14 10:33:27 localhost(?

My logger config

private Logger configureLogger(String appenderName, String loggerName, SyslogAppender syslogAppender) {
try {
if (syslogAppender != null) {
syslogAppender.start();
getConfig().addAppender(syslogAppender);
AppenderRef[] refs = new AppenderRef[]{AppenderRef.createAppenderRef(appenderName, null, null)};
LoggerConfig loggerConfig = LoggerConfig.createLogger("false", Level.DEBUG, loggerName,
"true", refs, null, getConfig(), null);
loggerConfig.addAppender(syslogAppender, null, null);
getConfig().removeLogger(loggerName);
getConfig().addLogger(loggerName, loggerConfig);
getContext().updateLoggers();
return getContext().getLogger(loggerName);
}
} catch (IllegalStateException e) {
LOGGER.error("An error occurred while configuring syslog settings");
LOGGER.trace("Exception: ", e);
throw e;
}
return null;
}

这是我的SyslogAppender配置

private SyslogAppender createSyslogAppender(ReportingSendProtocolType protocol, ReportingFacilityType reportingFacilityType, String host, int port, boolean ignoreExceptions, String appenderName, Configuration config) {
return SyslogAppender.createAppender(host,
port,
protocol.name(),
null,
0,
0,
true,
appenderName,
true,
ignoreExceptions,
Facility.toFacility(reportingFacilityType.name()),
null,
Rfc5424Layout.DEFAULT_ENTERPRISE_NUMBER,
true,
null,
null,
null,
true,
null,
null,
null,
null,
null,
null,
null,
null,
config,
Charset.forName("UTF-8"),
null,
new LoggerFields[]{},
true); //false
}

您只需要配置PatternLayout,它只是消息格式。

。艾凡:

此模式将向您显示时间戳和类(由"t"表示)

%d{HH:mm:ss.SSS} [%t]

如果您只想显示消息,模式看起来像:

%msg%n

关于模式的更多信息:https://logging.apache.org/log4j/2.x/manual/configuration.html

为了添加到您的代码中,您在这里有一个示例:
PatternLayout layout= PatternLayout.createLayout(PATTERN, null, null, Charset.defaultCharset(),false,false,null,null);
Appender appender=ConsoleAppender.createAppender(layout, null, null, "CONSOLE_APPENDER", null, null);
appender.start();
getConfig().addAppender(appender);

希望对大家有用

这是我的解决方案。我重写SyslogAppender和buildLayout()如下:

public class MySyslogAppender extends SyslogAppender {
@Override
public Layout<ILoggingEvent> buildLayout() {
if (suffixPattern == null) {
suffixPattern = DEFAULT_SUFFIX_PATTERN;
}
PatternLayout layout = new PatternLayout();
layout.setPattern(suffixPattern);
layout.setContext(getContext());
layout.start();
return layout;
}
}

在logback。xml

应用这个类
<appender name="syslog" class="MySyslogAppender"/>

可以正常使用后缀pattern,不再使用时间和主机前缀。我认为如果以编程方式创建MySyslogAppender也很有用。

最新更新