NCron 默认记录器写入事件日志,抛出安全异常

本文关键字:安全 异常 日志 默认 记录器 入事件 NCron | 更新日期: 2023-09-27 17:56:56

Simple NCron service:

class Program
{
    static void Main(string[] args)
    {
        var schedService = new SchedulingService();
        schedService.At("* * * * *").Run<MyTask>(); // run every minute
        schedService.Start();
        Console.ReadLine();
    }
}
public class MyTask : NCron.ICronJob
{
    public void Execute()
    {
        Console.WriteLine("executing");
    }
    public void Initialize(NCron.CronContext context)
    {
    }
    public void Dispose()
    {
    }
}

在到达第一分钟但在执行MyTask之前,NCron似乎想要写入Windows事件日志,并失败了

Unhandled Exception: System.Security.SecurityException: The source was not found, but some or all event logs could not be searched.  To create the source, you need permission to read all event logs to make sure that the new source name is unique.  Inaccessible logs: Security.
   at System.Diagnostics.EventLogInternal.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate)
   at System.Diagnostics.EventLogInternal.SourceExists(String source, String machineName, Boolean wantToCreate)
   at System.Diagnostics.EventLogInternal.VerifyAndCreateSource(String sourceName, String currentMachineName)
   at System.Diagnostics.EventLogInternal.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
   at System.Diagnostics.EventLog.WriteEntry(String message, EventLogEntryType type)
   at NCron.ExceptionHelper.LogUnhandledException(Object exception)
   at NCron.Service.SchedulingService.WaitCallbackHandler(Object data)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()`

NCron 写入事件日志的内容和原因? 这是默认行为,所以我想任何使用 NCron 的人都必须处理过这个问题,但我找不到有关该问题的任何文档或问题/答案。 我尝试设置schedService.LogFactory = null;,这不会改变任何东西。

除了创建自定义日志工厂(我不想这样做)或摆弄注册表(我真的不想这样做,有时无法在生产机器上),我该如何解决这个问题?

NCron 默认记录器写入事件日志,抛出安全异常

如果不想写入事件日志,则需要提供备用记录器和工厂。 如 https://code.google.com/p/ncron/wiki/Logging 页面底部所述,有一个 log4net 实现可用,其中最新版本似乎位于 https://github.com/schourode/ncron/tree/master/src/NCron.Integration.log4net。 如果你不想使用 log4net,那么编写一个替代实现将是相当简单的。

如果愿意允许 NCron 写入事件日志,则可以通过在运行服务之前在管理员帐户下创建目标事件日志来避免运行时 SecurityException。 这通常是通过在安装程序中包含事件日志的创建来完成的(假设您有一个),例如通过使用 EventLogInstaller。