码迷,mamicode.com
首页 > Windows程序 > 详细

使用Topshelf创建Windows服务,服务中使用log4net记录日志

时间:2018-04-19 13:57:10      阅读:322      评论:0      收藏:0      [点我收藏+]

标签:location   encoding   datetime   files   proc   led   cep   splay   enc   

一、新建一个控制台应用程序

二、使用nuget引用 TopShelf和log4net插件

三、log4net配置文件添加

  在根目录增加log4net.config文件和logHelper类库的添加

   log4net.config内容如下:

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

  <log4net>
    <!--信息日志配置-->
    <appender name="InfoLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" type=""  value="Log\\Info\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxSizeRollBackups" value="20"/>
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd‘.log‘" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d  [%5p] %c: %m%n" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter,log4net">
        <levelMin value="INFO" />
        <levelMax value="INFO" />
      </filter>
    </appender>
    <!--错误日志配置-->
    <appender name="ErrorLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" type=""  value="Log\\Error\\" />
      <param name="AppendToFile" value="true" />
      <param name="MaxSizeRollBackups" value="20"/>
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="yyyy-MM-dd‘.log‘" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d  [%5p] %c: %m%n" />
      </layout>
      <filter type="log4net.Filter.LevelRangeFilter,log4net">
        <levelMin value="ERROR" />
        <levelMax value="ERROR" />
      </filter>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="ErrorLogFileAppender" />
      <appender-ref ref="InfoLogFileAppender" />
    </root>
    <logger name="ALL" >
      <level value="ALL" />
      <appender-ref ref="ErrorLogFileAppender"></appender-ref>
      <appender-ref ref="InfoLogFileAppender"></appender-ref>
    </logger>
  </log4net>
</configuration>

  logHelper类库:

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WindowsService1
{
    public class LogHelper
    {
        public static ILog GetLog<T>(T t)
        {
            ILog _log = LogManager.GetLogger("");
            if (t != null)
            {
                _log = LogManager.GetLogger(t.GetType());
            }
            return _log;
        }
    }
}

 

四、编写服务功能类【每3秒打印一个日志】

using log4net;
using System;
using System.IO;
using System.Reflection;
using System.Timers;

namespace WindowsService1
{
    public class TestWriteDate
    {
        readonly Timer _timer;
        public TestWriteDate()
        {
            _timer = new Timer(3000)
            {
                AutoReset = true,
                Enabled = true
            };
            _timer.Elapsed += delegate (object sender, System.Timers.ElapsedEventArgs e)
            {
                LogHelper.GetLog(this).Info(string.Format("DATE: {0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
                LogHelper.GetLog(this).Error("测试出错!!!", new Exception("dfsafdsafddsafdsa"));
                try
                {
                    int i = 0;
                    int j = 10 / i;
                }
                catch (Exception ex)
                {
                    LogHelper.GetLog(this.GetType()).Error(ex.Message, ex);
                }
            };
        }

        public void Start()
        {
            LogHelper.GetLog(this).Info("开始执行");
        }

        public void Stop()
        {
            LogHelper.GetLog(this).Info(string.Format("结束执行") + Environment.NewLine + Environment.NewLine);
            _timer.AutoReset = false;
            _timer.Enabled = false;
        }
    }
}

 

五、与TopShelf集成

  Program.cs的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using Topshelf;

namespace WindowsService1
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        static void Main()
        {
            string assemblyFilePath = Assembly.GetExecutingAssembly().Location;
            string assemblyDirPath = Path.GetDirectoryName(assemblyFilePath);
            string configFilePath = assemblyDirPath + "\\log4net.config";
            log4net.Config.XmlConfigurator.Configure(new FileInfo(configFilePath));
            HostFactory.Run(c =>
            {
                c.Service<TestWriteDate>((x) =>
                {
                    x.ConstructUsing(name => new TestWriteDate());
                    x.WhenStarted((t) => t.Start());
                    x.WhenStopped((t) => t.Stop());
                });
                c.RunAsLocalSystem();
                //服务描述
                c.SetDescription("TEST_SERVICES");
                //服务显示名称
                c.SetDisplayName("TEST_SERVICES");
                //服务的真实名称
            });
        }
    }
}

  六、服务的安装与卸载

  1、安装 install.bat

@echo begin...
cd /d %~dp0
WindowsService1.exe install
net start TEST_SERVICES
pause

  2、卸载 uninstall.bat

@echo unInstall...
cd /d %~dp0
WindowsService1.exe uninstall
pause

  七、源码

  点击下载 

 

使用Topshelf创建Windows服务,服务中使用log4net记录日志

标签:location   encoding   datetime   files   proc   led   cep   splay   enc   

原文地址:https://www.cnblogs.com/wjx-blog/p/8881804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!