log4net 使用
作者:互联网
一、在nuget中搜索log4net,然后直接安装
二、无论是CS还是BS都可以在AssemblyInfo.cs文件里添加以下的语句:
[assembly: log4net.Config .XmlConfigurator(ConfigFile ="log4net.config")]
还有ConfigFileExtension(配置文件的扩展名) 和 Watch(表示是否监视该配置文件)
或者建一个类,CS端在Main方法中调用,BS在Global.asax.cs的Application_Start方法中调用
public class LogHelper { static LogHelper() { var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config"); XmlConfigurator.Configure(logCfg); } private static LogHelper _instance = null; private static ILog ILog; public static ILog Log(Type t) { if (_instance == null) _instance = new LogHelper(); ILog = LogManager.GetLogger(t); return ILog; } public static ILog Log(string type) { if (_instance == null) _instance = new LogHelper(); ILog = LogManager.GetLogger(type); return ILog; } }View Code
注意配置文件必须要放到bin下面的目录里
三、配置文件
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <appender name="FileAppender" type="log4net.Appender.RollingFileAppender"> <file value="log\" /> <appendToFile value="true" /> <rollingStyle value="Date" /> <datePattern value="yyyyMMdd'.log'" /> <staticLogFileName value="false" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> <root> <level value="ALL" /> <appender-ref ref="FileAppender" /> </root> </log4net> </configuration>View Code
还有很多配置可以参考
http://logging.apache.org/log4net/release/config-examples.html
四、调用
class Program { static void Main(string[] args) { Console.WriteLine("dfasdfas"); ILog log = LogHelper.Log(typeof(Program)); log.Info("dadafds"); log.Debug("debug"); } }View Code
标签:log4net,配置文件,instance,static,使用,LogHelper,ILog 来源: https://www.cnblogs.com/ZJ199012/p/11200512.html