使用NLog的Windows服务

我正在创建一个Windows服务,我想使用NLog。 我希望将日志写入服务的安装位置,如下所示:

PathToInstalledService\Logs\MyLog.txt 

这当然需要管理员的权益。 所以我的问题是,在为服务创建安装时,我应该在ServiceProcessInstaller上使用什么帐户。 我一直在使用LocalService,但此帐户没有所需的高程。

谢谢。

在安装过程中,您应该更改“日志”目录的权限,以允许您的服务帐户写入文件。 使用具有执行服务function所需的最少权限的帐户,通常是NETWORK SERVICE帐户。

您可以从服务上的安装类执行此操作:

  void Installer1_AfterInstall(object sender, InstallEventArgs e) { string myAssembly = Path.GetFullPath(this.Context.Parameters["assemblypath"]); string logPath = Path.Combine(Path.GetDirectoryName(myAssembly), "Logs"); Directory.CreateDirectory(logPath); ReplacePermissions(logPath, WellKnownSidType.NetworkServiceSid, FileSystemRights.FullControl); } static void ReplacePermissions(string filepath, WellKnownSidType sidType, FileSystemRights allow) { FileSecurity sec = File.GetAccessControl(filepath); SecurityIdentifier sid = new SecurityIdentifier(sidType, null); sec.PurgeAccessRules(sid); //remove existing sec.AddAccessRule(new FileSystemAccessRule(sid, allow, AccessControlType.Allow)); File.SetAccessControl(filepath, sec); }