簡體   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