Created
August 2, 2015 05:59
-
-
Save davidalpert/afc94b716fab31c69149 to your computer and use it in GitHub Desktop.
Per-Instance logging with NLog & TopShelf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Timers; | |
using FubuCore; | |
using NLog; | |
using NLog.Layouts; | |
using NLog.Targets; | |
using Topshelf; | |
using Topshelf.Runtime; | |
namespace Dragon.WindowsService | |
{ | |
public class TownCrier | |
{ | |
readonly Timer _timer; | |
public TownCrier(HostSettings settings) | |
{ | |
_timer = new Timer(1000) { AutoReset = true }; | |
_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now); | |
} | |
public void Start() { _timer.Start(); } | |
public bool Stop(HostControl hostControl) | |
{ | |
_timer.Stop(); | |
return true; | |
} | |
public void ShutDown(HostControl control) | |
{ | |
Stop(control); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
HostFactory.Run(x => | |
{ | |
x.Service<TownCrier>(s => | |
{ | |
s.ConstructUsing(settings => | |
{ | |
ReconfigureNLog(settings); | |
return new TownCrier(settings); | |
}); | |
s.WhenStarted(tc => tc.Start()); | |
s.WhenStopped((tc, control) => tc.Stop(control)); | |
s.WhenShutdown((tc, control) => tc.ShutDown(control)); | |
}); | |
x.RunAsLocalSystem(); | |
x.UseNLog(); | |
x.SetDescription("Sample Topshelf Host"); | |
x.SetDisplayName("Stuff"); | |
x.SetServiceName("Stuff"); | |
}); | |
} | |
private static void ReconfigureNLog(HostSettings settings) | |
{ | |
var target = LogManager.Configuration.FindTargetByName("file") as FileTarget; | |
if (target != null && string.IsNullOrWhiteSpace(settings.InstanceName) == false) | |
{ | |
var customLogFileName = "log.{0}.".ToFormat(settings.ServiceName); | |
target.FileName = (target.FileName as SimpleLayout).Text.Replace("log.", customLogFileName); | |
target.ArchiveFileName = (target.ArchiveFileName as SimpleLayout).Text.Replace("log.", customLogFileName); | |
LogManager.ReconfigExistingLoggers(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment