Log4net入门(简要介绍)
Log4net是Apache公司的log4j?的.NET版本,用于帮助.NET开发人员将日志信息输出到各种不同的输出源(Appender),常见的输出源包括控制台、日志文件和数据库等。本篇主要讨论如何在控制台应用程序中将日志文件输出到控制台、日志文件和SQL Server数据库中。
1 使用Visual Studio创建一个控制台应用
2 在Nuget中下载log4net
3.增加App.config(app.config)配置文件
注意,一定要叫App.config或者app.config,不然程序识别不到 具体的配置可以查看资料,:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net>
<root>
<level value="ALL" />
<appender-ref ref="RollingFileAppender" />
<appender-ref ref="ConsoleAppender" />
</root>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Log/" />
<appendToFile value="true" />
<RollingStyle value="Composite" />
<MaxSizeRollBackups value="-1" />
<datePattern value="yyyy-MM"/"yyyyMMdd".txt"" />
<staticLogFileName value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<maximumFileSize value="2MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%t]%-5p %c - %m%n" />
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
</log4net>
</configuration>
4 增加工具类和默认配置
新建Logger.cs
using System.Diagnostics;
using log4net.Config;
using System.Reflection;
using System.Text;
using log4net;
namespace ConsoleApp1
{
public class Logger
{
Logger(ILog log)
{
this._log = log;
}
private readonly log4net.ILog _log;
static Logger()
{
Console.WriteLine("初始化日志配置完成");
XmlConfigurator.Configure();
}
public static Logger GetLogger(Type? type)
{
log4net.ILog log = log4net.LogManager.GetLogger(type);
Logger logger = new Logger(log);
return logger;
}
public void info(string message)
{
if (_log.IsInfoEnabled)
{
_log.Info(message);
}
}
public void debug(string message)
{
if (_log.IsDebugEnabled)
{
_log.Debug(message);
}
}
public void debug(Exception ex)
{
if (_log.IsDebugEnabled)
{
_log.Debug(ex.Message + "/r/n" + ex.Source + "/r/n" +
ex.TargetSite + "/r/n" + ex.StackTrace);
}
}
public void error(string message)
{
if (_log.IsErrorEnabled)
{
_log.Error(message);
}
}
public void error(Exception ex)
{
if (_log.IsErrorEnabled)
{
_log.Error(ex.Message, ex);
}
}
public void error(string message, Exception ex)
{
if (_log.IsErrorEnabled)
{
_log.Error(message, ex);
}
}
}
}
5 测试
|