Log4j 日志记录到单独的文件 [英] Log4j logging to separate files

查看:53
本文介绍了Log4j 日志记录到单独的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在特定端口上侦听以执行其任务的应用程序.通过指定不同的实例,此应用程序可以在多个实例上运行参数中的端口.

I have an application that listens on a specific port to do its task. This application can run on multiple instances by specifying different ports in the argument.

MyApp-1211.bat包含

MyApp-1211.bat contains

java MyApp 1211

MyApp-1311.bat包含

MyApp-1311.bat contains

java MyApp 1311

MyApp-1411.bat包含

MyApp-1411.bat contains

java MyApp 1411

此应用程序记录到文件.问题是所有三个实例的日志放入单个文件 myApp.log .有没有办法告诉log4j使用不同的日志文件?像:

This application logs to a file. The problem is all three instances log into a single file, myApp.log. Is there a way to tell log4j to use different log files? like:

myApp-port1211.log  
myApp-port1311.log  
myApp-port1411.log  

推荐答案

当然可以.一种方法是创建多个配置文件(log4j.xml/log4j.properties)-每个端口分别处理一个.加载配置文件后,您可以根据当前端口号选择正确的文件:

Of course you can. One way would be to create multiple configuration files (log4j.xml / log4j.properties) - one per port respectively process. Upon loading the configuration file you could select the correct one based on the current port number:

PropertyConfigurator.configure("log4j-" + port + ".properties");

相应地创建配置文件: log4j-1211.properties log4j-1311.properties ,...

Create the config files accordingly: log4j-1211.properties, log4j-1311.properties, ...

另一种选择是在运行时通过Java代码配置文件记录:

The alternative would be to configure the file logging at runtime via Java code:

String logFilename = "./myApp-port" + port + ".log";
Layout layout = new PatternLayout("%d{ISO8601} %-5p [%t] %c{1}: %m%n");
FileAppender fileAppender = new FileAppender(layout, logFilename, false);
fileAppender.setThreshold(Level.DEBUG);
Logger.getRootLogger().addAppender(fileAppender);

这篇关于Log4j 日志记录到单独的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆