一、log4net简单实例创建步骤如下
1、第一步:在项目中添加对log4net.dll的引用,这里引用版本是2.0.8.0
2、第二步:程序启动时读取log4net的配置文件。
读取log4net的配置文件有两种方式
(1)如果是CS程序,在根目录的Program.cs中的Main方法中添加:log4net.Config.XmlConfigurator.Configure();
如果是BS程序,在根目录的Global.asax.cs(没有新建一个)中的Application_Start方法中添加:log4net.Config.XmlConfigurator.Configure();
(2)无论BS还是CS程序都可直接在项目的AssemblyInfo.cs文件里添加以下的语句:[assembly: log4net.Config .XmlConfigurator()]
3、第三步:在程序使用。
二、具体代码解析
1、建立日志级别枚举
public enum ELogLevel
{
/// <summary>
/// 错误信息
/// </summary>
Error = ,
/// <summary>
/// 跟踪信息
/// </summary>
Trace = ,
/// <summary>
/// 调试信息
/// </summary>
Debug = ,
/// <summary>
/// 记录信息
/// </summary>
Info =
}
2、定义ILog接口
public interface ILogger : IDisposable
{
void LogWithTime(string msg, ELogLevel logLevel = ELogLevel.Error);
bool Enabled { get; set; }
}
3、实现ILog接口并且通过代码读取log4net.xml
public class FileLogger : ILogger
{
private log4net.ILog _log = null;
private string _configLogLevel = null;
private bool _enabled = true; public FileLogger()
{
this._configLogLevel = GetAppSettingValue("LogLevel");
string logName = GetAppSettingValue("LogName");
string configPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.xml");
log4net.Config.XmlConfigurator.Configure(new FileInfo(configPath));
this._log = log4net.LogManager.GetLogger(logName);
}
/// <summary>
/// 获取AppSetting的值
/// </summary>
/// <returns></returns>
public static string GetAppSettingValue(string key)
{
string value = null;
foreach (string item in System.Configuration.ConfigurationManager.AppSettings)
{
if (item.Equals(key, StringComparison.CurrentCultureIgnoreCase))
{
value = System.Configuration.ConfigurationManager.AppSettings[key];
break;
}
}
return value;
} #region ILogger成员
public void LogWithTime(string msg, ELogLevel logLevel)
{
if (string.IsNullOrWhiteSpace(msg) || !this._enabled)
{
return;
}
#if DEBUG
Trace.TraceInformation(msg);
#endif
if (string.IsNullOrWhiteSpace(this._configLogLevel))
{
this._configLogLevel = ((int)ELogLevel.Error).ToString();
}
int configLogLevel = Convert.ToInt32(this._configLogLevel);
if ((int)logLevel <= configLogLevel)
{
try
{
switch (logLevel)
{
case ELogLevel.Error:
this._log.Error(msg);
break;
case ELogLevel.Trace:
this._log.Warn(msg);
break;
case ELogLevel.Debug:
this._log.Debug(msg);
break;
case ELogLevel.Info:
this._log.Info(msg);
break;
default:
break;
}
}
catch
{
}
}
} public bool Enabled
{
get { return this._enabled; }
set { this._enabled = value; }
}
#endregion #region IDisposable
public void Dispose()
{ }
#endregion
}
4、使用log4net
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void btnLog4net_Click(object sender, EventArgs e)
{
ILogger _fileLogger = new FileLogger();
_fileLogger.LogWithTime("log4net 日志记录",ELogLevel.Info);
MessageBox.Show("生成的日志地址:"+System.AppDomain.CurrentDomain.BaseDirectory);
}
}
三、log4net.xml配置
<?xml version="1.0" encoding="utf-8" ?>
<log4net debug="true">
<appender name="FlatFile" type="log4net.Appender.RollingFileAppender,log4net">
<param name="File" value="logs/website.log" />
<param name="Encoding" value="utf-8" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="ImmediateFlush" value="true" />
<param name="MaximumFileSize" value="50MB"/>
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<param name="DatePattern" value="-yyyy.MM.dd'.log'" />
<param name="StaticLogFileName" value="true" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%-5level [%logger] - %message [%date] %newline" />
</layout>
</appender>
<root>
<priority value="DEBUG" />
<appender-ref ref="FlatFile" />
</root>
</log4net>
四、注意事项
在Debug模式一切正常,但是在release模式下log4net不工作,查了很多资料,终于解决。具体做如下检查修改。
1、检查log4net写入日志文件路径是否正确;
2、检查对应日志文件路径是否有权限;
3、检查程序log4net配置获取路径;
最常见的问题是第三步,一般都是在AssemblyInfo.cs文件中写入如下代码
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.xml", ConfigFileExtension = "xml", Watch = true)]
但这个方式在Debug模式下没有问题,但是在release模式下就不好用了,需要在Global.asax文件中具体再次指定配置文件所在位置,例如:
string configPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "log4net.xml");
log4net.Config.XmlConfigurator.Configure(new FileInfo(configPath));
重新编译发布就可以了。
下一篇介绍NLog日志