zl程序教程

您现在的位置是:首页 >  其他

当前栏目

log4net 单独项目

项目 单独 Log4net
2023-09-11 14:21:23 时间

首先参考:http://blog.csdn.net/feiying008/article/details/45440547


有时,我们需要将日志功能作为单独模块,用来以后嫁接到其他项目。

今天就来看看如何将日志作为单独项目。


首先,通过Nuget下载log4net.

然后创建一个类库项目,作为log4net通用项目

如下



AssemblyInfo.cs 增加 

[assembly: log4net.Config.XmlConfigurator(ConfigFile="log4net.config", Watch = true)]


LogerHelper:

public class LogerHelper
    {
        public static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebLog");
        public static void WriteLog(string info)
        {
            if (log.IsInfoEnabled)
            {
                log.Info(info);
            }
        }
    }


在 看我们的主项目,主项目添加Common的引用。



创建log4net.config文件。

属性中,选择复制到输出目录--> 始终复制


配置信息:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>

  <!--log4net-->
  <log4net>
    <root>
      <appender-ref ref="WebLog" />
    </root>
    <appender name="WebLog" type="log4net.Appender.RollingFileAppender,log4net">
      <file value="Log/" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <datePattern value="yyyy-MM-dd&quot;.log&quot;" />
      <maxSizeToRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <conversionPattern value="%d - %-5level - %c - %m%n" />
      </layout>
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    </appender>
  </log4net>
  
    <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-1.2.15.0" newVersion="1.2.15.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>


然后调用就可以了

public ActionResult Index()
        {
            LogerHelper.WriteLog("123");
            return View();
        }