Skip to content

Commit

Permalink
Adding standard template with DI\Config\Logging included
Browse files Browse the repository at this point in the history
  • Loading branch information
bishopsmove committed Mar 30, 2018
1 parent 585f77c commit e3e4a35
Show file tree
Hide file tree
Showing 9 changed files with 274 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -23,7 +23,7 @@ Follow up with this
```
mkdir NameOfYourProject
cd NameOfYourProject
dotnet new mcrsvc-min
dotnet new [ mcrsvc-min | mcrsvc-std ]
```
This will create a sample project for you. Next chapter explains its features in more details especially points 6 onwards if you used the template.

Expand Down
6 changes: 6 additions & 0 deletions Solution/DotNetCore.WindowsService.sln
Expand Up @@ -14,6 +14,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
..\.editorconfig = ..\.editorconfig
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PeterKottas.DotNetCore.WindowsService.StandardTemplate", "..\Source\Templates\PeterKottas.DotNetCore.WindowsService.StandardTemplate\PeterKottas.DotNetCore.WindowsService.StandardTemplate.csproj", "{6B26C0CE-CB7C-49FA-92F6-4B13D3881E51}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -32,6 +34,10 @@ Global
{D5FE4BD5-85F0-42D8-89D7-C8AF272278F3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D5FE4BD5-85F0-42D8-89D7-C8AF272278F3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D5FE4BD5-85F0-42D8-89D7-C8AF272278F3}.Release|Any CPU.Build.0 = Release|Any CPU
{6B26C0CE-CB7C-49FA-92F6-4B13D3881E51}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6B26C0CE-CB7C-49FA-92F6-4B13D3881E51}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6B26C0CE-CB7C-49FA-92F6-4B13D3881E51}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6B26C0CE-CB7C-49FA-92F6-4B13D3881E51}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
@@ -0,0 +1,12 @@
{
"author": "Peter Kottas",
"classifications": [ "Microservices", "Console", "Boilerplate", "Dependency Injection", "Logging", "Configuration" ],
"name": "Microservice - Standard w/ DI, Configuration and Logging Extensions",
"identity": "PeterKottas.DotNetCore.WindowsService.StandardTemplate",
"tags": {
"language": "C#"
},
"shortName": "mcrsvc-std",
"guids": [ "dc46e9be-12b0-43c5-ac94-5c7019d59196" ],
"sourceName": "PeterKottas.DotNetCore.WindowsService.StandardTemplate"
}
@@ -0,0 +1,45 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using PeterKottas.DotNetCore.WindowsService.Base;
using PeterKottas.DotNetCore.WindowsService.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace PeterKottas.DotNetCore.WindowsService.StandardTemplate
{
public class ExampleService : MicroService, IMicroService
{
private IMicroServiceController _controller;
private ILogger<ExampleService> _logger;

public ExampleService()
{
_controller = null;
}

public ExampleService(IMicroServiceController controller, ILogger<ExampleService> logger)
{
_controller = controller;
_logger = logger;
}


public void Start()
{
StartBase();
Timers.Start("Poller", 1000, () =>
{
_logger.LogInformation(string.Format("Polling at {0}\n", DateTime.Now.ToString("o")));
});
_logger.LogTrace("Started\n");
}

public void Stop()
{
StopBase();
_logger.LogTrace("Stopped\n");
}
}
}
@@ -0,0 +1,79 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace PeterKottas.DotNetCore.WindowsService.StandardTemplate
{
// Thanks to Andrew Lock for basic details needed here: https://andrewlock.net/creating-a-rolling-file-logging-provider-for-asp-net-core-2-0/
public class LogFileProvider : ILoggerProvider
{
public ILogger CreateLogger(string categoryName)
{
return new FileLogger(this, categoryName);
}

public void Dispose()
{
// TODO: Handle File IO mechanics
}

public void AddMessage(DateTimeOffset timestamp, string message)
{
// TODO: Handle File IO mechanics
}
}

public class FileLogger : ILogger
{
LogFileProvider _provider;
string _category;
public FileLogger(LogFileProvider provider, string categoryName)
{
_provider = provider;
_category = categoryName;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}

public bool IsEnabled(LogLevel logLevel)
{
if (logLevel == LogLevel.None)
{
return false;
}
return true;
}

public void Log<TState>(DateTimeOffset timestamp, LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}

var builder = new StringBuilder();
builder.Append(timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff zzz"));
builder.Append(" [");
builder.Append(logLevel.ToString());
builder.Append("] ");
builder.Append(_category);
builder.Append(": ");
builder.AppendLine(formatter(state, exception));

if (exception != null)
{
builder.AppendLine(exception.ToString());
}

_provider.AddMessage(timestamp, builder.ToString());
}

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
Log(DateTimeOffset.Now, logLevel, eventId, state, exception, formatter);
}
}
}
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.0.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.0.1" />
<PackageReference Include="Microsoft.Extensions.PlatformAbstractions" Version="1.1.0" />
<PackageReference Include="PeterKottas.DotNetCore.WindowsService" Version="2.0.6" />
</ItemGroup>

<ItemGroup>
<None Update="appsettings.Development.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>


</Project>
@@ -0,0 +1,73 @@
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace PeterKottas.DotNetCore.WindowsService.StandardTemplate
{
class Program
{
public static void Main(string[] args)
{
#if !DEBUG
var configuration = new ConfigurationBuilder()
.SetBasePath(PlatformServices.Default.Application.ApplicationBasePath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
#else
var configuration = new ConfigurationBuilder()
.SetBasePath(PlatformServices.Default.Application.ApplicationBasePath)
.AddJsonFile("appsettings.Development.json", optional: false, reloadOnChange: true)
.Build();
#endif

var svcProvider = new ServiceCollection()
.AddLogging(builder =>
{
builder
.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace)
.AddProvider(new LogFileProvider()); // Implemented vanilla LogFile provider but is easily swapped for Nlog or SeriLog (et al.) providers
})
.AddOptions()
.AddSingleton(new LoggerFactory()
.AddConsole())
.BuildServiceProvider();

var _logger = svcProvider.GetRequiredService<ILoggerFactory>().CreateLogger<Program>();


ServiceRunner<ExampleService>.Run(config =>
{
var name = config.GetDefaultName();
config.Service(serviceConfig =>
{
serviceConfig.ServiceFactory((extraArguments, controller) =>
{
return new ExampleService(controller, svcProvider.GetRequiredService<ILoggerFactory>().CreateLogger<ExampleService>());
});
serviceConfig.OnStart((service, extraParams) =>
{
_logger.LogTrace("Service {0} started", name);
service.Start();
});
serviceConfig.OnStop(service =>
{
_logger.LogTrace("Service {0} stopped", name);
service.Stop();
});
serviceConfig.OnError(e =>
{
_logger.LogError(e, string.Format("Service {0} errored with exception", name));
});
});
});
}
}
}
@@ -0,0 +1,12 @@
{
"ConnectionString": {
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
@@ -0,0 +1,18 @@
{
"ConnectionString": {

},
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
}
}

0 comments on commit e3e4a35

Please sign in to comment.