Windows Service with NLog

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

PathToInstalledService\Logs\MyLog.txt

      

This will, of course, require administrator rights. So my question is, when creating an installation for a Service, which account should be used in the ServiceProcessInstaller. I am currently using LocalService, but this account does not have the required level.

Thank.

+2


source to share


1 answer


During installation, you must change the permissions of the Logs directory so that your service account writes files. Use the account with the least privilege necessary to perform your service, usually the NETWORK SERVICE account.

You can do this from an installation class in a 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);
    }

      

+7


source







All Articles