Skip to content

Instantly share code, notes, and snippets.

@janpieterz
Created March 4, 2015 13:03
Show Gist options
  • Save janpieterz/33ae2312350fe5605e97 to your computer and use it in GitHub Desktop.
Save janpieterz/33ae2312350fe5605e97 to your computer and use it in GitHub Desktop.
Serilog and Topshelf
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