Windows Service with NLog

让人想犯罪 __ 提交于 2019-12-21 05:56:05

问题


I am creating a Windows Service which I want to use NLog with. I want the logs to be written to the install location of the service say something like:

PathToInstalledService\Logs\MyLog.txt

This is of course going to require administrator priveledges. So my question is, when creating the install for the Service, what account should I use on the ServiceProcessInstaller. I have been currently using LocalService, but this account does not have the required elevation.

Thanks.


回答1:


During installation you should change the permissions of the 'Logs' directory to allow your service account to write files. Use the account with the least privileges needed to perform your services function, generally the NETWORK SERVICE account.

You can do this from an install class on the 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);
    }


来源:https://stackoverflow.com/questions/1567513/windows-service-with-nlog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!