log4net 记录到数据库和本地文件
1)配置代码
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/> </configSections> <log4net> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <!--日志路径--> <param name= "File" value= "D:\App_Log\G2\"/> <!--是否是向文件中追加日志--> <param name= "AppendToFile" value= "true"/> <!--log保留天数--> <param name= "MaxSizeRollBackups" value= "10"/> <!--日志文件名是否是固定不变的--> <param name= "StaticLogFileName" value= "false"/> <!--日志文件名格式为:2008-08-31.log--> <param name= "DatePattern" value= "yyyy-MM-dd".read.log""/> <!--日志根据日期滚动--> <param name= "RollingStyle" value= "Date"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n %loggername" /> </layout> </appender> <!--<logger name="WebLogger"> <level value="INFO"/> <appender-ref ref="ADONetAppender" /> </logger>--> <!--<logger name="WebTest"> <level value="INFO"/> <appender-ref ref="ADONetTest" /> </logger>--> <!--SQL数据库--> <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender"> <bufferSize value="1"/> <!-- SQL数据源 --> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <!-- SQL连接字符串--> <connectionString value="data source=xxx.sqlserver.rds.aliyuncs.com,13433;initial catalog=dbtest;integrated security=False;persist security info=True;User ID=sa;Password=123" /> <commandText value="INSERT INTO ErrLog ([RecordTime],[LevelName],[Message],[Exception],[UserID]) VALUES (@log_date, @log_level, @message, @exception, @UserID)"/> <parameter> <parameterName value="@log_date"/> <dbType value="DateTime"/> <layout type="log4net.Layout.RawTimeStampLayout"/> </parameter> <parameter> <parameterName value="@log_level"/> <dbType value="String"/> <size value="50"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level"/> </layout> </parameter> <parameter> <parameterName value="@exception"/> <dbType value="String"/> <size value="2000"/> <layout type="log4net.Layout.ExceptionLayout"/> </parameter> <parameter> <parameterName value="@message"/> <dbType value="String"/> <size value="4000"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message"/> </layout> </parameter> <!--自定义成员 --> <parameter> <parameterName value="@UserID" /> <dbType value="Int32" /> <layout type="G2.Log.CustomLayout"> <conversionPattern value="%UserId" /> </layout> </parameter> </appender> <root> <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) --> <level value="all" /> <appender-ref ref="ADONetAppender"/> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/> </startup> </configuration>
2)LogHelper
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using log4net; using log4net.Core; using log4net.Layout.Pattern; namespace G2.Log { public class LogMessage { public string Message { get; set; } public int UserId { get; set; } public override string ToString() { return Message; } } public class CustomLayout : log4net.Layout.PatternLayout { public CustomLayout() { this.AddConverter("UserId", typeof(UserIdPatternConverter)); } } internal sealed class UserIdPatternConverter : PatternLayoutConverter { override protected void Convert(TextWriter writer, LoggingEvent loggingEvent) { var logMessage = loggingEvent.MessageObject as LogMessage; if (logMessage != null) { writer.Write(logMessage.UserId); } } } public class LogHelper { public static string Path = System.Configuration.ConfigurationManager.AppSettings["log4net"] ; public static string LoggerName = System.Configuration.ConfigurationManager.AppSettings["loggerName"]; static LogHelper() { if (string.IsNullOrEmpty(Path)) { Path = AppDomain.CurrentDomain.BaseDirectory + "log4net.config"; } if (string.IsNullOrEmpty(LoggerName)) { LoggerName = "G2.Core"; } } private static ILog _log; public static ILog Log { get { if (_log == null) { string path = Path; log4net.Config.XmlConfigurator.Configure(new FileInfo(path)); _log = log4net.LogManager.GetLogger(LoggerName); } return _log; } } /// <summary> /// 调试 /// </summary> public static void Debug(LogMessage message) { if (Log.IsDebugEnabled) { Log.Debug(message); } } /// <summary> /// 错误 /// </summary> public static void Error(LogMessage message, Exception ex) { if (Log.IsErrorEnabled) { Log.Error(message,ex); } } /// <summary> /// 严重错误 /// </summary> public static void Fatal(LogMessage message, Exception ex) { if (Log.IsFatalEnabled) { Log.Fatal(message); } } /// <summary> /// 记录一般日志 /// </summary> public static void Info(LogMessage message) { if (Log.IsInfoEnabled) { Log.Info(message); } } /// <summary> /// 记录警告 /// </summary> public static void Warn(LogMessage message) { if (Log.IsWarnEnabled) { Log.Warn(message); } } /// <summary> /// 需要写日志的地方调用此方法 /// </summary> /// <param name="level">自定义级别</param> /// <param name="logMessage">日志消息</param> /// <param name="ex">异常</param> public static void SaveMessage(LogLevel level,LogMessage logMessage, Exception ex) { switch (level) { case LogLevel.Debug : Debug(logMessage); break; case LogLevel.Info: Info(logMessage); break; case LogLevel.Warn: Warn(logMessage); break; case LogLevel.Error: Error(logMessage,ex); break; case LogLevel.Fatal: Fatal(logMessage,ex); break; default: break; } } } public enum LogLevel { Debug=0, Info=1, Warn=2, Error=3, Fatal=4 } }
3)调用
class Program { static void Main(string[] args) { LogMessage log=new LogMessage(); log.UserId = 19; log.Message = "asdfasd"; try { throw new Exception("一个空的引用对象"); } catch (Exception ex) { LogHelper.SaveMessage( LogLevel.Error,log,ex); } Console.Read(); } }