Created
March 4, 2015 13:03
-
-
Save janpieterz/33ae2312350fe5605e97 to your computer and use it in GitHub Desktop.
Serilog and 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.IO; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using Serilog; | |
using Serilog.Extras.Topshelf; | |
using Topshelf; | |
using Topshelf.Logging; | |
namespace ConsoleApplication1 | |
{ | |
public class Program | |
{ | |
static int Main(string[] args) | |
{ | |
ILogger configuration = new LoggerConfiguration() | |
.WriteTo.ColoredConsole() | |
.WriteTo.RollingFile(@"Log-{Date}.txt") | |
.CreateLogger(); | |
StreamWriter writer = | |
new StreamWriter(File.Open(@"c:\temp\seriself.txt", FileMode.Append, FileAccess.Write, | |
FileShare.ReadWrite)); | |
Serilog.Debugging.SelfLog.Out = writer; | |
Task.Factory.StartNew(() => | |
{ | |
while (true) | |
{ | |
writer.Flush(); | |
Thread.Sleep(1000); | |
} | |
}); | |
return (int)HostFactory.Run(x => | |
{ | |
x.UseSerilog(configuration); | |
x.SetDescription("Sample Topshelf Service hosting"); | |
x.SetDisplayName("Example"); | |
x.SetServiceName("Example"); | |
x.Service<ExampleControl>(sc => | |
{ | |
sc.ConstructUsing(() => new ExampleControl()); | |
sc.WhenStarted((s, hostControl) => s.Start(hostControl)); | |
sc.WhenStopped((s, hostControl) => s.Stop(hostControl)); | |
}); | |
x.StartAutomatically(); | |
}); | |
} | |
} | |
public class ExampleControl : ServiceControl | |
{ | |
private static readonly LogWriter Log = HostLogger.Get<ExampleControl>(); | |
public bool Start(HostControl hostControl) | |
{ | |
Log.Info("Starting"); | |
return true; | |
} | |
public bool Stop(HostControl hostControl) | |
{ | |
Log.Info("Stopping"); | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment