Skip to content
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

Added NLogBuilder and ASP.NET Core 2 example #191

Merged
merged 3 commits into from
Oct 12, 2017
Merged
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
12 changes: 8 additions & 4 deletions NLog.Web.AspNetCore/AspNetExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public static LoggingConfiguration ConfigureNLog(this IHostingEnvironment env, s
/// <summary>
/// Apply NLog configuration from XML config.
/// </summary>
/// <param name="fileName">absolute path NLog configuration file.</param>
/// <param name="fileName">Path to NLog configuration file, e.g. nlog.config. </param>
/// <returns>LoggingConfiguration for chaining</returns>
private static LoggingConfiguration ConfigureNLog(string fileName)
{
Expand Down Expand Up @@ -88,16 +88,20 @@ public static IWebHostBuilder UseNLog(this IWebHostBuilder builder, NLogAspNetCo
{
ServiceLocator.ServiceProvider = serviceProvider;

//register yourself
ConfigurationItemFactory.Default.RegisterItemsFromAssembly(typeof(AspNetExtensions).Assembly);

NLogBuilder.RegisterNLogWebAspNetCore();

LogManager.Configuration?.Reload();
return new NLogLoggerFactory(options);

});
//note: this one is called before services.AddSingleton<ILoggerFactory>
if (options.RegisterHttpContextAccessor)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}





});
Expand Down
2 changes: 2 additions & 0 deletions NLog.Web.AspNetCore/NLog.Web.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
<GenerateAssemblyVersionAttribute>false</GenerateAssemblyVersionAttribute>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Version>4.4.1</Version>
<RootNamespace>NLog.Web</RootNamespace>
</PropertyGroup>

<ItemGroup>
Expand All @@ -55,6 +56,7 @@
<PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Routing.Abstractions" Version="2.0.0" />
<PackageReference Include="NLog" Version="4.5.0-beta04" />

</ItemGroup>
<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion NLog.Web.AspNetCore/NLogAspNetCoreOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System.Text;
using NLog.Extensions.Logging;

namespace NLog.Web.AspNetCore
namespace NLog.Web
{
/// <summary>
/// Options for ASP.NET Core and NLog
Expand Down
60 changes: 60 additions & 0 deletions NLog.Web.AspNetCore/NLogBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#if NETSTANDARD2_0


using System;
using System.Collections.Generic;
using System.Reflection;
using NLog.Common;
using NLog.Config;

namespace NLog.Web
{


/// <summary>
/// NLog helper for ASP.NET Standard 2
/// </summary>
public static class NLogBuilder
{
/// <summary>
/// Register NLog.Web.AspNetCore, so so &lt;extension&gt; in NLog's config isn't needed.
/// </summary>
internal static void RegisterNLogWebAspNetCore()
{
try
{
InternalLogger.Debug("Registering NLog.Web.AspNetCore");
ConfigurationItemFactory.Default.RegisterItemsFromAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly);
}
catch (Exception ex)
{
InternalLogger.Error(ex, "Registering NLog.Web.AspNetCore failed");
}

}

/// <summary>
/// Configure NLog
/// </summary>
/// <param name="fileName">Path to NLog configuration file, e.g. nlog.config. </param>>
/// <returns>LogFactory to get loggers, add events etc</returns>
public static LogFactory ConfigureNLog(string fileName)
{
RegisterNLogWebAspNetCore();
return ConfigureNLog(new XmlLoggingConfiguration(fileName));
}

/// <summary>
/// Configure NLog
/// </summary>
/// <param name="configuration"></param>
/// <returns>LogFactory to get loggers, add events etc</returns>
public static LogFactory ConfigureNLog(LoggingConfiguration configuration)
{
RegisterNLogWebAspNetCore();
LogManager.Configuration = configuration;
return LogManager.LogFactory;
}
}
}
#endif
14 changes: 13 additions & 1 deletion NLog.Web.sln
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26403.7
VisualStudioVersion = 15.0.26730.16
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{52CA242D-DB20-41D9-8B79-A5A965ECA105}"
EndProject
Expand All @@ -12,6 +12,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NLog.Web.AspNetCore", "NLog
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NLog.Web.AspNetCore.Tests", "NLog.Web.AspNetCore.Tests\NLog.Web.AspNetCore.Tests.csproj", "{C02D4CED-0098-4526-BB95-6AB9D988036D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ASP.NET Core 2 - VS2017", "examples\ASP.NET Core 2\Visual Studio 2017\ASP.NET Core 2 - VS2017\ASP.NET Core 2 - VS2017.csproj", "{D43A99EE-F27F-4552-9E23-C9686809AC3D}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Examples", "Examples", "{A9FB260C-9052-45D3-827A-20590F9D2FEF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -34,6 +38,10 @@ Global
{C02D4CED-0098-4526-BB95-6AB9D988036D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C02D4CED-0098-4526-BB95-6AB9D988036D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C02D4CED-0098-4526-BB95-6AB9D988036D}.Release|Any CPU.Build.0 = Release|Any CPU
{D43A99EE-F27F-4552-9E23-C9686809AC3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D43A99EE-F27F-4552-9E23-C9686809AC3D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D43A99EE-F27F-4552-9E23-C9686809AC3D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D43A99EE-F27F-4552-9E23-C9686809AC3D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -43,5 +51,9 @@ Global
{E318FB41-9712-44CA-B792-E865EFE1A564} = {52CA242D-DB20-41D9-8B79-A5A965ECA105}
{9E3F7ECB-A6ED-422E-8429-F96C510F59CF} = {52CA242D-DB20-41D9-8B79-A5A965ECA105}
{C02D4CED-0098-4526-BB95-6AB9D988036D} = {52CA242D-DB20-41D9-8B79-A5A965ECA105}
{D43A99EE-F27F-4552-9E23-C9686809AC3D} = {A9FB260C-9052-45D3-827A-20590F9D2FEF}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B8468549-60D6-49AC-A6F7-44391E4C392C}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"directory": "wwwroot/lib"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

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

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</ItemGroup>

<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\..\NLog.Web.AspNetCore\NLog.Web.AspNetCore.csproj" />
</ItemGroup>

<ItemGroup>
<Content Update="NLog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ASP.NET_Core_2___VS2017.Models;
using Microsoft.Extensions.Logging;

namespace ASP.NET_Core_2___VS2017.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;

//NLog: inject logger
public HomeController(ILogger<HomeController> logger)
{

_logger = logger;
}

public IActionResult Index()
{
_logger.LogInformation("Hello, this is the index!");
return View();
}

public IActionResult About()
{
ViewData["Message"] = "Your application description page.";

return View();
}

public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";

return View();
}

public IActionResult Error()
{
_logger.LogError("Ow noos! an error");
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;

namespace ASP.NET_Core_2___VS2017.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="info"
internalLogFile="c:\temp\internal-nlog.txt">


<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger}|${message} ${exception}" />

<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger}|${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

<!-- write to the void aka just remove -->
<target xsi:type="Null" name="blackhole" />
</targets>

<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />

<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Config;
using NLog.Web;

namespace ASP.NET_Core_2___VS2017
{
public class Program
{
public static void Main(string[] args)
{
// NLog: setup the logger first to catch all errors
var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger();
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@snakefoot updated it! I think is indeed a lot better.

@grokky1 any opinion on this? Do you think this is clear?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The latest changes are good. Looking forward to using this.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@grokky1 the beta is live. Please let me know of you're happy, rtm will be soon then. See also.https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@304NotModified Sorry busy wrapping up a sprint so didn't get a chance, will try soon!!

try
{
logger.Debug("init main");
BuildWebHost(args).Run();
}
catch (Exception e)
{
//NLog: catch setup errors
logger.Error(e, "Stopped program because of exception");
throw;
}
}

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseNLog() // NLog: setup NLog for Dependency injection
.Build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:56152/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"ASP.NET_Core_2___VS2017": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:56153/"
}
}
}
Loading