根据某些条件登录到不同的文件 [英] Logging into different files based on some condition
问题描述
我们有一个应用程序.在其中有一个条件.根据条件,如果为true,则将一些日志消息写入一个文件,否则将这些消息记录到另一个文件.
We have an application. In which we have a condition.Based on the condition, if it is true then we will write some log messages to one file else we will log the messages to another file.
应该根据条件而不是基于日志级别进行日志记录.
And logging should be happened based on the condition and not based on log level.
在使用Yaml文件的dropwizard中怎么可能?
How it is possible in dropwizard using yaml file?
推荐答案
开箱即用地支持此功能.这是我的示例:
This is supported out of the box. Here is my example:
server:
rootPath: /api/*
requestLog:
appenders: []
applicationConnectors:
- type: http
port: 9085
logging:
level: INFO
loggers:
"my-log-1":
level: DEBUG
additive: false
appenders:
- type: file
currentLogFilename: /home/artur/var/log/test1.log
archivedLogFilenamePattern: /home/artur/var/log/test1.log%d.log.gz
archivedFileCount: 5
logFormat: '[%level] %msg%n'
"my-log-2":
level: DEBUG
additive: false
appenders:
- type: file
currentLogFilename: /home/artur/var/log/test2.log
archivedLogFilenamePattern: /home/artur/var/log/test2.log%d.log.gz
archivedFileCount: 5
注意:您不能在配置中使用选项卡.
NOTE: You can not use tabs in the configuration.
此配置将创建2个记录器.第一个称为"my-log-1",第二个称为"my-log-2".
This configuration creates 2 loggers. First is called "my-log-1", second is called "my-log-2".
您现在可以在Java类中(例如在我的应用程序中)创建这些记录器:
You can now create these loggers in your java class, for example in my application:
public class Application extends io.dropwizard.Application<Configuration>{
private static final Logger log = Logger.getLogger("my-log-1");
private static final Logger log2 = Logger.getLogger("my-log-2");
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
log.info("Test1"); // writes to first file
log2.info("Test2"); // logs to seconds file
}
public static void main(String[] args) throws Exception {
new Application().run("server", "/home/artur/dev/repo/sandbox/src/main/resources/config/test.yaml");
}
}
在文件顶部注意两个记录器及其创建.
Note the two loggers and their creation at the top of the file.
您现在可以像使用任何记录器一样使用它们.添加您的条件并注销:
You can now use them like any logger. Add your condition and log away:
int random = new Random().nextInt();
if(random % 2 == 0) {
log.info("Test1"); // writes to first file
} else {
log2.info("Test2"); // logs to seconds file
}
我希望能回答您的问题,
I hope that answers your question,
谢谢
Artur
这篇关于根据某些条件登录到不同的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!