Skip to content

Added support for appsettings configuration #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions samples/ConfigurationWebSample/ConfigurationWebSample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\Serilog.AspNetCore\Serilog.AspNetCore.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="3.0.1" />
<PackageReference Include="Serilog.Settings.Configuration" Version="2.4.0" />
</ItemGroup>

</Project>
37 changes: 37 additions & 0 deletions samples/ConfigurationWebSample/Controllers/ScopesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace SimpleWebSample.Controllers
{
[Route("api/[controller]")]
public class ScopesController : Controller
{
ILogger<ScopesController> _logger;

public ScopesController(ILogger<ScopesController> logger)
{
_logger = logger;
}

// GET api/scopes
[HttpGet]
public IEnumerable<string> Get()
{
_logger.LogInformation("Before");

using (_logger.BeginScope("Some name"))
using (_logger.BeginScope(42))
using (_logger.BeginScope("Formatted {WithValue}", 12345))
using (_logger.BeginScope(new Dictionary<string, object> { ["ViaDictionary"] = 100 }))
{
_logger.LogInformation("Hello from the Index!");
_logger.LogDebug("Hello is done");
}

_logger.LogInformation("After");

return new string[] { "value1", "value2" };
}
}
}
19 changes: 19 additions & 0 deletions samples/ConfigurationWebSample/Controllers/ValuesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Serilog;

namespace SimpleWebSample.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
// Directly through Serilog
Log.Information("This is a handler for {Path}", Request.Path);
return new string[] { "value1", "value2" };
}
}
}
41 changes: 41 additions & 0 deletions samples/ConfigurationWebSample/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using Microsoft.AspNetCore;

namespace SimpleWebSample
{
public class Program
{
public static int Main(string[] args)
{
try
{
BuildWebHost(args).Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog(configuration =>
new Serilog.LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger()
)
.Build();

}
}
35 changes: 35 additions & 0 deletions samples/ConfigurationWebSample/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace SimpleWebSample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseMvc();
}
}
}
7 changes: 7 additions & 0 deletions samples/ConfigurationWebSample/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"Serilog": {
"MinimumLevel": {
"Default": "Debug"
}
}
}
17 changes: 17 additions & 0 deletions samples/ConfigurationWebSample/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "Console"
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
}
}
9 changes: 8 additions & 1 deletion serilog-aspnetcore.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.10
VisualStudioVersion = 15.0.26730.16
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A1893BD1-333D-4DFE-A0F0-DDBB2FE526E0}"
EndProject
Expand All @@ -24,6 +24,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.AspNetCore", "src\S
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Serilog.AspNetCore.Tests", "test\Serilog.AspNetCore.Tests\Serilog.AspNetCore.Tests.csproj", "{AD51759B-CD58-473F-9620-0B0E56A123A1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConfigurationWebSample", "samples\ConfigurationWebSample\ConfigurationWebSample.csproj", "{527FE86F-B74A-434C-BA00-82F693260390}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -42,6 +44,10 @@ Global
{AD51759B-CD58-473F-9620-0B0E56A123A1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AD51759B-CD58-473F-9620-0B0E56A123A1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AD51759B-CD58-473F-9620-0B0E56A123A1}.Release|Any CPU.Build.0 = Release|Any CPU
{527FE86F-B74A-434C-BA00-82F693260390}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{527FE86F-B74A-434C-BA00-82F693260390}.Debug|Any CPU.Build.0 = Debug|Any CPU
{527FE86F-B74A-434C-BA00-82F693260390}.Release|Any CPU.ActiveCfg = Release|Any CPU
{527FE86F-B74A-434C-BA00-82F693260390}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -50,6 +56,7 @@ Global
{69F9A0ED-7910-4F33-8919-28BB05376FBC} = {F2407211-6043-439C-8E06-3641634332E7}
{0549D23F-986B-4FB2-BACE-16FD7A7BC9EF} = {A1893BD1-333D-4DFE-A0F0-DDBB2FE526E0}
{AD51759B-CD58-473F-9620-0B0E56A123A1} = {E30F638E-BBBE-4AD1-93CE-48CC69CFEFE1}
{527FE86F-B74A-434C-BA00-82F693260390} = {F2407211-6043-439C-8E06-3641634332E7}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {811E61C5-3871-4633-AFAE-B35B619C8A10}
Expand Down
14 changes: 14 additions & 0 deletions src/Serilog.AspNetCore/AspNetCore/SerilogLoggerFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,30 @@
// See the License for the specific language governing permissions and
// limitations under the License.

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog.Debugging;
using Serilog.Extensions.Logging;
using System;

namespace Serilog.AspNetCore
{
class SerilogLoggerFactory : ILoggerFactory
{
readonly SerilogLoggerProvider _provider;

public SerilogLoggerFactory(IConfiguration configuration, Func<IConfiguration, Serilog.ILogger> loggerBuilder, bool setCoreLogger = true, bool dispose = false)
{
var logger = loggerBuilder(configuration);

if (setCoreLogger)
{
Serilog.Log.Logger = logger;
}

_provider = new SerilogLoggerProvider(logger, dispose);
}

public SerilogLoggerFactory(Serilog.ILogger logger = null, bool dispose = false)
{
_provider = new SerilogLoggerProvider(logger, dispose);
Expand Down
18 changes: 18 additions & 0 deletions src/Serilog.AspNetCore/SerilogWebHostBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Microsoft.Extensions.Logging;
using Serilog.AspNetCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;

namespace Serilog
{
Expand All @@ -41,5 +42,22 @@ public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Serilog.I
collection.AddSingleton<ILoggerFactory>(new SerilogLoggerFactory(logger, dispose)));
return builder;
}

/// <summary>
/// Sets Serilog as the logging provider from the configuration.
/// </summary>
/// <param name="builder">The web host builder to configure.</param>
/// <param name="loggerBuilder">The function to build the logger</param>
/// <param name="setCoreLogger">If true, set the static <see cref="Serilog.Log"/> from the built logger.</param>
/// <param name="dispose">When true, dispose the created logger when the framework disposes the provider.</param>
/// <returns>The web host builder.</returns>
public static IWebHostBuilder UseSerilog(this IWebHostBuilder builder, Func<IConfiguration, Serilog.ILogger> loggerBuilder,
bool setCoreLogger = true, bool dispose = false)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
builder.ConfigureServices((context, collection) =>
collection.AddSingleton<ILoggerFactory>(new SerilogLoggerFactory(context.Configuration, loggerBuilder, setCoreLogger, dispose)));
return builder;
}
}
}