window服务中配置值Log4Net(转载)

 

转载来源 https://www.cnblogs.com/Can-daydayup/p/10223239.html

 https://www.cnblogs.com/skyheaving/p/12294241.html

 

一、需求:

  C#window服务下添加一个日志记录

 

 

二、添加和使用步骤如下:

下载并引入Log4Net.dll程序集到项目中

  下载地址:http://logging.apache.org/log4net/download_log4net.cgi

方法一:下载,然后放到包文件夹(packages)里。

方案二:NuGet 安装

 

执行命令:

 Install-Package  log4net

然后packages 就有log4net编译好的dll文件了  

 

 

最后选中引用,右键,添加引用

 

 

 

 

 浏览去packages文件,选中 log4net.dll文件,最后点击确定

 

 

 

 

在App.Config中添加对应的节点

<!--重点configsections必须是第一个节点1og4net配置-->
<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>

 在App.Config中添加Log4Net.dll初始化信息(主要一些按照什么格式存储,存储位置的配置)

复制代码
  <log4net>
  <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
  <!-- Set root logger level to ERROR and its appenders -->
  <root>
  <level value="ALL" />
  <appender-ref ref="SysAppender" />
  </root>
  <!-- Print only messages of level DEBUG or above in the packages -->
  <logger name="WebLogger">
  <level value="DEBUG" />
  </logger>
  <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
  <!--日志文件夹名称-->
  <param name="File" value="ProJectsLogs/" />
  <param name="AppendToFile" value="true" />
  <param name="RollingStyle" value="Date" />
  <param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;" />
  <param name="StaticLogFileName" value="false" />
  <layout type="log4net.Layout.PatternLayout,log4net">
  <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
  </layout>
  </appender>
  <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
  <layout type="log4net.Layout.PatternLayout,log4net">
  <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
  </layout>
  </appender>
  </log4net>
复制代码

 实际应用中App.config改动:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <root>
      <appender-ref ref="RollingLogFileAppender" />
      <appender-ref ref="ConsoleAppender" />
    </root>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="[%date] %level [%thread][%c{1}:%line] - %m%n" />
      </layout>
    </appender>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <!--日志存放位置 ~/..-->
      <param name="File" value="logs\\" />
      <!--追加到文本末尾-->
      <param name="AppendToFile" value="true" />
      <!--最多产生的日志文件数,超过则只保留最新的n个。设定值value="-1"为不限文件数-->
      <param name="MaxSizeRollBackups" value="50" />
      <!--最大文件大小-->
      <param name="MaximumFileSize" value="5MB"/>
      <param name="RollingStyle" value="Date" />
      <!--文件命名方式-->
      <param name="DatePattern" value="yyyy-MM-dd'.log'" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout">
        
        <conversionPattern value="[%date] %level [%thread][%c{1}:%line]  %n%m%n" />
      </layout>
    </appender>
  </log4net>
  
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <appSettings>
    <add key="website" value="www.baidu.com" />
    <add key="user" value="UserName" />
    <add key="password" value="Password" />
    <add key="localFilePath" value="D:ftp\data" />
    <add key="nameList" value="AWS_30min.dat,AWS_10min.dat,TMS_10min.dat,TMS_30min.dat" />
  </appSettings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

  <connectionStrings>

    <add name="FarmWeatherEntities" connectionString="metadata=res://*/FarmWeather.csdl|res://*/FarmWeather.ssdl|res://*/FarmWeather.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=FarmWeather;persist security info=True;user id=sa;password=yjcd8923459565;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
    
  </connectionStrings>


</configuration>

 

在Properties-AssemblyInfo.cs:配置文件中读取配置Log4net.dll

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

 或者

 [assembly: log4net.Config.XmlConfigurator(Watch = true)]

 

使用Log4Net.Dll记录日志

复制代码
//首先实例化Log4net
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

//使用记录信息
log.Debug("Debug", new Exception("Debug"));
log.Info("Info", new Exception("Info"));
log.Warn("Warn", new Exception("Warn"));
log.Error("Error", new Exception("Error"));
log.Fatal("Fatal", new Exception("Fatal"));
复制代码

 实际应用中可以封装成一个类

    public class LogManage
    {

        private static readonly ILog logger = LogManager.GetLogger(typeof(LogManage));
        static LogManage()
        {

            BasicConfigurator.Configure();
        }

        public static void Error(Exception ex)
        {
            logger.Error(ex.Message, ex);
        }

        public static void Error(string msg)
        {
            logger.Error(msg);
        }
        public static void Error(string msg,Exception ex)
        {
            logger.Error(msg,ex);
        }

        public static void Info(string msg)
        {
            logger.Info(msg);
        }
    }

  调用

LogManage.Info("导入程序正常结束");

  LogManage.Error(new Exception("异常测试"));

 LogManage.Error("异常标题", new Exception("异常测试"));

 

 

posted @ 2021-01-05 17:45  hao_1234_1234  阅读(202)  评论(0编辑  收藏  举报