.net 日志系统官网: https://logging.apache.org/
有了log4j2的基础,log4net使用也类似,很容易让JAVA程序员上手。
1.通过NuGet下载依赖包 log4net 2.0.8
2.创建配置文件 log4net.config,放置到源代码src下,要运行起来要放到/bin/Debug/ /bin/Release 下,并在文件AssemblyInfo.cs上加上一句:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
log4net.config 正文内容如下:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net debug="true"> <root> <level value="DEBUG" /> <appender-ref ref="RollingLogFileAppender" /> <appender-ref ref="ConsoleAppender" /> </root> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" > <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="[%date] %level [%thread][%c{1}:%line] - %m%n" /> </layout> </appender> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender" > <param name="File" value="game" /> <param name="DatePattern" value="'.'yyyy-MM-dd-HH'.log'" /> <param name="AppendToFile" value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="[%date] %level [%thread][%c{1}:%line] - %m%n" /> </layout> </appender> </log4net> </configuration>
日志文件会在/bin/Debug下生成,当前的日志为game,历史的比如game.2017-08-11-19.log。
3.代码中如何使用
using log4net; private static readonly ILog logger = LogManager.GetLogger(typeof(GameClient)); Thread.CurrentThread.Name = "main";//为了让主线程名显示 //初始化log4net log4net.Config.XmlConfigurator.Configure(); logger.Debug("初始化连接开始"); logger.InfoFormat("测试日志 name={0}","client");
打印出来的结果如下:
[2017-08-11 20:18:19,350] DEBUG [main][GameClient:24] - 初始化连接开始 [2017-08-11 20:18:19,363] DEBUG [main][GameClient:28] - 初始化连接完毕 [2017-08-11 20:18:19,364] INFO [main][SuperSocketDemo:35] - 测试日志 name=client
对于JAVA程序员来说,是不是感觉很完美?