![](/img/trans.png)
[英]Windows Service: Where to write log messages (EventLog, File or DB Table) / Access from Web
[英]How to write to eventLog with NLog from a dynamically loaded dll in a windows service
如何从Windows服务中动态加载的dll中使用NLog写入eventLog。
使用NLog 2.0.1,我有一个Windows服务,该服务会动态加载一个dll,该dll是我正在(尝试)使用NLog记录到EventLog的那个dll中的。 eventLog是自定义的,由服务安装程序创建。
错误:
Service cannot be started. System.Reflection.TargetInvocationException:
Exception has been thrown by the target of an invocation.
---> System.TypeInitializationException: The type initializer for 'MyService.Worker' threw an exception.
---> NLog.NLogConfigurationException: Error during initialization of EventLog Target[eventLog_wrapped]
---> System.IO.IOException: The network path was not found.
at Microsoft.Win32.RegistryKey.Win32ErrorStatic(Int32 errorCode, String str)
at Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(RegistryHive hKey, String machineName, RegistryView view)
at System.Diagnostics.EventLog.GetEventLogRegKey(String machine, Boolean writable)
at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate)
at System.Diagnostics.EventLog._InternalLogNameFromSourceName(String source, String machineName)
at System.Diagnostics.EventLog.LogNameFromSourceName(String source, String machineName)
at NLog.Targets.EventLogTarg...
我创建了一个winForm应用程序来测试日志记录,并且日志记录按预期方式工作,但是当我尝试在服务中执行相同操作时,它将无法正常工作。
我尝试在“本地系统”和“网络服务”下运行该服务,但出现相同的错误。 至于“网络路径...”,没有网络路径被访问,所以我不确定这试图告诉我什么。
我的NLog配置/目标是:
<variable name="appName" value="MyApp" />
<variable name="source" value="MySource" />
<target xsi:type="EventLog"
name="log"
log="My Service"
source="${source}"
machineName="."
layout="${callsite}${newline} ${message}${newline}${exception:format=ToString}"
/>
任何想法如何使这项工作将不胜感激。
好吧,令人尴尬,但也许它将为某人节省一些时间。
简短的答案,nlog.config文件位于错误的目录中。
该解决方案有两个项目,即服务主机/安装程序项目和完成逻辑/工作的项目。 服务从服务主机/安装程序的debug文件夹安装(仍在早期测试中)。 逻辑dll由服务hsot从逻辑项目调试文件夹中加载。 逻辑文件夹包含nlog.config。 因此,当服务启动时,在服务主机运行的位置找不到nlog.config文件。
服务主机没有引用service.dll,这不是问题,因为dll是在运行时加载的,但是nlog.config文件是一个问题。
创建服务的简单解决方案是将逻辑/工作项目输出更改为与服务主机输出目录相同。
尝试创建EventLog并设置SourceKilobytes(如果源不存在)时,我遇到了System.TypeInitializationException。
通过在创建EventLog对象之前移动EventLog.CreateEventSource()来解决。
if (!EventLog.SourceExists(SOURCE)) {
EventLog.CreateEventSource(SOURCE, LOG);
}
eventLog = new EventLog();
eventLog.Source = SOURCE;
eventLog.Log = LOG;
eventLog.MachineName = System.Environment.MachineName;
eventLog.MaximumKilobytes = 1024;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.