繁体   English   中英

Windows服务启动,然后停止,但没有日志记录

[英]Windows Service started and then stopped, but no logging

昨天,我将可执行文件C:\\Users\\urban\\Documents\\Visual Studio 2013\\Projects\\TestService\\obj\\Release\\TestService.exe作为服务安装在Windows 10中,因此现在显示在services.msc 然后,我启动了该错误消息,就像

本地计算机上的“服务名称”服务启动,然后停止。 如果某些服务未被其他服务或程序使用,则会自动停止。

今天,我回到VS,添加EventLog并尝试... catch,这样我的代码现在看起来像这样:

internal class TestService : ServiceBase
{
    Thread Worker;
    AutoResetEvent StopRequest = new AutoResetEvent(false);
    Toolkit toolkit;

    protected override void OnStart(string[] args)
    {
        try {
            EventLog.Log = "Application";
            EventLog.Source = "TestService";
            EventLog.WriteEntry("Starting Test Service", EventLogEntryType.Information);
            var User = System.Security.Principal.WindowsPrincipal.Current;
            toolkit = new ServiceToolkit(User);
            Worker = new Thread(DoWork);
            Worker.Start();
        }
        catch (Exception e)
        {
            EventLog.WriteEntry(e.GetType().Name + ": " + e.Message, EventLogEntryType.Error);
            throw;
        }
    }

我编译了它,并尝试从services.msc启动它。 尽管错误消息仍然相同,但我希望该服务至少记录它已启动以及引发了哪个错误。 但是娜达 在启动服务之前,我已经清除了事件查看器的“应用程序”协议,与此同时添加的一些日志也不来自我的服务。

这里发生了什么?

如果在安装服务时知道所有事件源,建议您提前注册这些源,然后就可以获取日志条目。 在这种情况下,您可以创建自己的简单记录器,该记录器可以灵活地提供您指定的日志。

这是我与服务一起使用的记录器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

    namespace TestWindowService
    {
        public static class MyLogger
        {
            public static void WriteErrorLog(Exception ex)
            {
                StreamWriter sw = null;
                try
                {
                    sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
                    sw.WriteLine(DateTime.Now.ToString() + ": " + ex.Source.ToString().Trim() + "; " + ex.Message.ToString().Trim());
                    sw.Flush();
                    sw.Close();
                }
                catch
                {
                }
            }

            public static void WriteErrorLog(string Message)
            {
                StreamWriter sw = null;
                try
                {
                    sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
                    sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
                    sw.Flush();
                    sw.Close();
                }
                catch
                {
                }
            }
        }
    }

我只用它

MyLogger.WriteErrorLog("Test window service started!");

停止服务时只需编写它。 您可以确定错误/原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM