在Windows服务中使用EventLog组件纪录日志

1,在Service1.cs文件的设计窗口中添加工具EventLog

 private static Timer timer = new Timer();
        public Service1()
        {
            InitializeComponent();
               if (!System.Diagnostics.EventLog.SourceExists("MySource"))
           {
                 System.Diagnostics.EventLog.CreateEventSource(
                    "MySource", "MyNewLog");
           }
               eventLog1.Source = "MySource";
               eventLog1.Log = "MyNewLog";
 
        }

        protected override void OnStart(string[] args)
        {
              // TODO: 在此处添加代码以启动服务。  
            //初始化Timers
            timer.Interval = 12000;

            eventLog1.WriteEntry("开始日志纪录");

          
                  String s = System.DateTime.Now.ToString();  
                if(!File.Exists(@"C:\Users\ITCA\Desktop\MyWindowsServiceTest.txt"))  
                {
                     StreamWriter sr = File.CreateText(@"C:\Users\ITCA\Desktop\MyWindowsServiceTest.txt");  
                       sr.WriteLine("-------------------------START SRV---------------------");  
                       sr.WriteLine ("我的新服务在{0}时间开始",s);  
                      sr.WriteLine ("我可以写整型 {0} or 浮点型 {1},等等.",1, 4.2);
                      sr.Close(); 
               }  
                  else 
               {  
                      StreamWriter sr = File.AppendText(@"C:\Users\ITCA\Desktop\MyWindowsServiceTest.txt");  
                      sr.WriteLine("-------------------------START SRV---------------------");  
                      sr.Close();  
                 }

                timer.Enabled = true;
                timer.Start();
                timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);



        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            using (StreamWriter sw=File.AppendText (@"C:\Users\ITCA\Desktop\MyWindowsServiceTest.txt"))
            {
                sw.WriteLine("----------------"+DateTime.Now.ToString ()+"---------------------"+"\r\n");

                eventLog1.WriteEntry("-------------日志纪录中-----------------------");
            }
        }

        protected override void OnStop()
        {

             // TODO: 在此处添加代码以执行停止服务所需的关闭操作。

            //结束定时
            timer.Enabled = false;
            timer.Stop();
            eventLog1.WriteEntry("日志纪录结束");
                        String s1 = System.DateTime.Now.ToString();
                        if (!File.Exists(@"C:\Users\ITCA\Desktop\MyWindowsServiceTest.txt"))  
                       {  
                         StreamWriter sr = File.CreateText(@"C:\Users\ITCA\Desktop\MyWindowsServiceTest.txt");  
                         sr.WriteLine("-------------------------STOP SRV---------------------");  
                         sr.WriteLine ("我的新服务在{0}时间停止",s1);  
                        sr.Close();  
                       }  
                        else 
                        {  
                        StreamWriter sr = File.AppendText(@"C:\Users\ITCA\Desktop\MyWindowsServiceTest.txt");  
                        sr.WriteLine("-------------------------STOP SRV---------------------");  
                        sr.WriteLine ("我的新服务在{0}时间停止",s1);  
                        sr.Close();  
                        }
         


        }
}

  在

  public Service1()
        {
            InitializeComponent();
               if (!System.Diagnostics.EventLog.SourceExists("MySource"))
           {
                 System.Diagnostics.EventLog.CreateEventSource(
                    "MySource", "MyNewLog");
           }
               eventLog1.Source = "MySource";
               eventLog1.Log = "MyNewLog";
 
        }

  中 Service1的构造函数中  判断是否已经存在事件源MySource 如果存在指定EventLog的属性Source 和Log  这两个属性是自定义的  不存在就创建一个 System.Diagnostics.EventLog.CreateEventSource(                     "MySource", "MyNewLog");

                  在这里 事件源MySource并不须要我们写什么代码 它只是一个自定义的字符串 在   事件查看器  下  windows日志下

          应用程序中 显示  的日记来源 就是我们自定义的 MySource 

         系统中        (如果卸载了此服务 后会有一个来源为Eventlog的日志,任务类型为 日志清除 【在添加组件并设置eventlog属性时有一个属性 显示 卸载此服务时是否 清除日志】)

                      打开这个来源为Eventlog的日志         显示信息为  MyNewLog日志文件已被清除

然后在OnStart()和OnStop()方法中写自己的逻辑代码

在服务开启或关闭时时    eventlog1.WriteEntity("这里是写入日志的自定义内容");

也可以在定时器中 每隔一段时间报告状态  ,

2,在Service1.Designer.cs文件中时vs在我们 创建服务时自动生成的代码  

 partial class Service1
    {
        /// <summary> 
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region 组件设计器生成的代码

        /// <summary> 
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.eventLog1 = new System.Diagnostics.EventLog();
            ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
            // 
            // Service1
            // 
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.ServiceName = "MyWindowsService";
            ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();

        }

        #endregion

        private System.Diagnostics.EventLog eventLog1;

    }

  

在 组件设计器生成的代码  中

   #region 组件设计器生成的代码

        /// <summary> 
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.eventLog1 = new System.Diagnostics.EventLog();
            ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
            // 
            // Service1
            // 
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.ServiceName = "MyWindowsService";
            ((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();

        }

        #endregion

  添加  //             // Service1             //          

   this.CanPauseAndContinue = true;   //服务是否可以暂停 并在再继续      

    this.CanShutdown = true;     //系统关闭时通知服务

        this.ServiceName = "MyWindowsService";//指定服务名为  创建服务的项目名称

3,生服务组件  在Service1.cs中右击 

添加安装程序

单击eventlog组件  右击

添加安装程序

生成ProjectInstaller.cs文件

4,ProjectInstaller.cs文件中  选中组件  右击设置属性

            serviceInstaller1 中ServiceName 为MyWindowsService

                                  StartType 中  设如何启动Manual 手动  Automatic自动

             serviceProcessInstaller1中 Account账户类型 设置为  LocaSystem  本地账户

5,编译  生成 

6,安装服务

原文地址:https://www.cnblogs.com/DamonTang/p/2413328.html