├── .gitattributes ├── .gitignore ├── LICENSE ├── NLog.Owin.Logging.Tests ├── LogAdapterCustomTranslationTable.cs ├── NLog.Owin.Logging.Tests.csproj ├── OwinDisabledLoggerTest.cs ├── OwinLoggerTest.cs ├── OwinLoggerTestBase.cs ├── OwinTestApp.cs ├── Properties │ └── AssemblyInfo.cs └── StartupStandard.cs ├── NLog.Owin.Logging.sln ├── NLog.Owin.Logging ├── Extensions.cs ├── NLog.Owin.Logging.csproj ├── NLog.snk ├── NLogAdapter.cs └── Properties │ └── AssemblyInfo.cs ├── NLog.snk ├── README.md └── appveyor.yml /.gitattributes: -------------------------------------------------------------------------------- 1 | # All files: detect if file is text automatically 2 | 3 | * text=auto 4 | 5 | # Text files that should be normalized to LF 6 | 7 | *.cs text diff=csharp 8 | *.config text 9 | *.sln text 10 | *.csproj text 11 | *.md text 12 | *.sh text 13 | *.ps1 text 14 | *.cmd text 15 | *.bat text 16 | *.markdown text 17 | *.msbuild text 18 | 19 | # Binary files that should not be normalized or diffed 20 | 21 | *.exe binary 22 | *.dll binary 23 | *.pdb binary 24 | *.pfx binary 25 | *.snk binary 26 | 27 | *.png binary 28 | *.gif binary 29 | *.jpg binary 30 | *.bmp binary 31 | *.ico binary 32 | 33 | *.chm binary 34 | *.7z binary 35 | *.zip binary 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | .vs/ 9 | 10 | # Build results 11 | [Dd]ebug/ 12 | [Dd]ebugPublic/ 13 | [Rr]elease/ 14 | [Rr]eleases/ 15 | x64/ 16 | x86/ 17 | build/ 18 | bld/ 19 | [Bb]in/ 20 | [Oo]bj/ 21 | 22 | # Roslyn cache directories 23 | *.ide/ 24 | 25 | # MSTest test Results 26 | [Tt]est[Rr]esult*/ 27 | [Bb]uild[Ll]og.* 28 | 29 | #NUNIT 30 | *.VisualState.xml 31 | TestResult.xml 32 | 33 | # Build Results of an ATL Project 34 | [Dd]ebugPS/ 35 | [Rr]eleasePS/ 36 | dlldata.c 37 | 38 | *_i.c 39 | *_p.c 40 | *_i.h 41 | *.ilk 42 | *.meta 43 | *.obj 44 | *.pch 45 | *.pdb 46 | *.pgc 47 | *.pgd 48 | *.rsp 49 | *.sbr 50 | *.tlb 51 | *.tli 52 | *.tlh 53 | *.tmp 54 | *.tmp_proj 55 | *.log 56 | *.vspscc 57 | *.vssscc 58 | .builds 59 | *.pidb 60 | *.svclog 61 | *.scc 62 | 63 | # Chutzpah Test files 64 | _Chutzpah* 65 | 66 | # Visual C++ cache files 67 | ipch/ 68 | *.aps 69 | *.ncb 70 | *.opensdf 71 | *.sdf 72 | *.cachefile 73 | 74 | # Visual Studio profiler 75 | *.psess 76 | *.vsp 77 | *.vspx 78 | 79 | # TFS 2012 Local Workspace 80 | $tf/ 81 | 82 | # Guidance Automation Toolkit 83 | *.gpState 84 | 85 | # ReSharper is a .NET coding add-in 86 | _ReSharper*/ 87 | *.[Rr]e[Ss]harper 88 | *.DotSettings.user 89 | 90 | # JustCode is a .NET coding addin-in 91 | .JustCode 92 | 93 | # TeamCity is a build add-in 94 | _TeamCity* 95 | 96 | # DotCover is a Code Coverage Tool 97 | *.dotCover 98 | 99 | # NCrunch 100 | _NCrunch_* 101 | .*crunch*.local.xml 102 | 103 | # MightyMoose 104 | *.mm.* 105 | AutoTest.Net/ 106 | 107 | # Web workbench (sass) 108 | .sass-cache/ 109 | 110 | # Installshield output folder 111 | [Ee]xpress/ 112 | 113 | # DocProject is a documentation generator add-in 114 | DocProject/buildhelp/ 115 | DocProject/Help/*.HxT 116 | DocProject/Help/*.HxC 117 | DocProject/Help/*.hhc 118 | DocProject/Help/*.hhk 119 | DocProject/Help/*.hhp 120 | DocProject/Help/Html2 121 | DocProject/Help/html 122 | 123 | # Click-Once directory 124 | publish/ 125 | 126 | # Publish Web Output 127 | *.[Pp]ublish.xml 128 | *.azurePubxml 129 | # TODO: Comment the next line if you want to checkin your web deploy settings 130 | # but database connection strings (with potential passwords) will be unencrypted 131 | *.pubxml 132 | *.publishproj 133 | 134 | # NuGet Packages 135 | *.nupkg 136 | # The packages folder can be ignored because of Package Restore 137 | **/packages/* 138 | # except build/, which is used as an MSBuild target. 139 | !**/packages/build/ 140 | # If using the old MSBuild-Integrated Package Restore, uncomment this: 141 | #!**/packages/repositories.config 142 | 143 | # Windows Azure Build Output 144 | csx/ 145 | *.build.csdef 146 | 147 | # Windows Store app package directory 148 | AppPackages/ 149 | 150 | # Others 151 | sql/ 152 | *.Cache 153 | ClientBin/ 154 | [Ss]tyle[Cc]op.* 155 | ~$* 156 | *~ 157 | *.dbmdl 158 | *.dbproj.schemaview 159 | *.pfx 160 | *.publishsettings 161 | node_modules/ 162 | 163 | # RIA/Silverlight projects 164 | Generated_Code/ 165 | 166 | # Backup & report files from converting an old project file 167 | # to a newer Visual Studio version. Backup files are not needed, 168 | # because we have git ;-) 169 | _UpgradeReport_Files/ 170 | Backup*/ 171 | UpgradeLog*.XML 172 | UpgradeLog*.htm 173 | 174 | # SQL Server files 175 | *.mdf 176 | *.ldf 177 | 178 | # Business Intelligence projects 179 | *.rdl.data 180 | *.bim.layout 181 | *.bim_*.settings 182 | 183 | # Microsoft Fakes 184 | FakesAssemblies/ 185 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016-2019 Yannic Staudt, NLog 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /NLog.Owin.Logging.Tests/LogAdapterCustomTranslationTable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using NUnit; 7 | using NUnit.Framework; 8 | using Microsoft.Owin.Testing; 9 | using Owin; 10 | using Microsoft.Owin.Logging; 11 | using Microsoft.Owin; 12 | using NLog.Config; 13 | using NLog.Targets; 14 | 15 | namespace NLog.Owin.Logging.Tests 16 | { 17 | public class StartupCustomTranslationTable 18 | { 19 | public void Configuration(IAppBuilder app) 20 | { 21 | // map all messages to Fatal log level 22 | app.UseNLog(tl => LogLevel.Fatal); 23 | 24 | app.Use(app); 25 | } 26 | } 27 | 28 | [TestFixture] 29 | public class OwinLoggerCustomTranslationTableTest 30 | { 31 | private TestServer _server; 32 | private DebugTarget _debugTarget; 33 | 34 | 35 | [OneTimeSetUp] 36 | public void FixtureInit() 37 | { 38 | _server = TestServer.Create(); 39 | 40 | // setup the debug target 41 | this._debugTarget = new DebugTarget { Layout = "${level} EventId:${event-properties:item=EventId} ${logger} ${callsite} ${message}" }; 42 | 43 | var loggingConfiguration = new LoggingConfiguration(); 44 | loggingConfiguration.AddTarget("debug", _debugTarget); 45 | loggingConfiguration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, _debugTarget)); 46 | 47 | LogManager.Configuration = loggingConfiguration; 48 | } 49 | 50 | [OneTimeTearDown] 51 | public void FixtureDispose() 52 | { 53 | _server.Dispose(); 54 | } 55 | 56 | [TestCase("/critical", "critical")] 57 | [TestCase("/error", "error")] 58 | [TestCase("/warning", "warning")] 59 | [TestCase("/information", "information")] 60 | [TestCase("/verbose", "verbose")] 61 | public async Task TestLogmessages(string route, string expectedMessageEnd) 62 | { 63 | var result = await _server.CreateRequest(route).GetAsync(); 64 | result.EnsureSuccessStatusCode(); 65 | 66 | // in this setup we should be redirecting all log messages to "Fatal".... 67 | Assert.That(_debugTarget.LastMessage, Does.StartWith("Fatal")); 68 | 69 | // note: the log messages end with watherver was logged thus we want to check for that 70 | Assert.That(_debugTarget.LastMessage, Does.EndWith(expectedMessageEnd)); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /NLog.Owin.Logging.Tests/NLog.Owin.Logging.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | net452 4 | NLog.Owin.Logging.Tests 5 | Copyright © 2016-2019 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /NLog.Owin.Logging.Tests/OwinDisabledLoggerTest.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | using NLog.Config; 3 | using NLog.Targets; 4 | using NUnit.Framework; 5 | 6 | namespace NLog.Owin.Logging.Tests 7 | { 8 | [TestFixture] 9 | public class OwinDisabledLoggerTest : OwinLoggerTestBase 10 | { 11 | private DebugTarget _debugTargetOnlyFatal; 12 | 13 | [OneTimeSetUp] 14 | public void InitConfig() 15 | { 16 | // setup the debug target 17 | _debugTargetOnlyFatal = new DebugTarget { Layout = "${level} ${message}" }; 18 | 19 | var loggingConfiguration = new LoggingConfiguration(); 20 | 21 | loggingConfiguration.AddTarget("debug-fatal-only", _debugTargetOnlyFatal); 22 | loggingConfiguration.LoggingRules.Add(new LoggingRule("*", LogLevel.Fatal, _debugTargetOnlyFatal)); 23 | 24 | LogManager.Configuration = loggingConfiguration; 25 | } 26 | 27 | 28 | /// 29 | /// Test logger which is only enabled for fatal/critical. 30 | /// 31 | /// 32 | /// 33 | /// 34 | [TestCase("/critical", 1)] 35 | [TestCase("/error", 0)] 36 | [TestCase("/warning", 0)] 37 | public async Task TestDisabledLogger(string route, int counterChange) 38 | { 39 | //also before empty 40 | var oldCounter = _debugTargetOnlyFatal.Counter; 41 | int callCount = 5; 42 | for (int i = 0; i < callCount; i++) 43 | { 44 | await CallRoute(route); 45 | } 46 | 47 | Assert.AreEqual(oldCounter + (counterChange * callCount), _debugTargetOnlyFatal.Counter); 48 | } 49 | 50 | } 51 | } -------------------------------------------------------------------------------- /NLog.Owin.Logging.Tests/OwinLoggerTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using NLog.Config; 4 | using NLog.Targets; 5 | using NUnit.Framework; 6 | 7 | namespace NLog.Owin.Logging.Tests 8 | { 9 | [TestFixture] 10 | public class OwinLoggerTest : OwinLoggerTestBase 11 | { 12 | private DebugTarget _debugTarget; 13 | 14 | [OneTimeSetUp] 15 | public void InitConfig() 16 | { 17 | // setup the debug target 18 | _debugTarget = new DebugTarget { Layout = "${level} EventId:${event-properties:item=EventId} ${logger} ${callsite} ${message}" }; 19 | 20 | var loggingConfiguration = new LoggingConfiguration(); 21 | loggingConfiguration.AddTarget("debug", _debugTarget); 22 | loggingConfiguration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, _debugTarget)); 23 | 24 | LogManager.Configuration = loggingConfiguration; 25 | } 26 | 27 | [TestCase("/critical", "critical", "Fatal")] 28 | [TestCase("/error", "error", "Error")] 29 | [TestCase("/warning", "warning", "Warn")] 30 | [TestCase("/information", "information", "Info")] 31 | [TestCase("/verbose", "verbose", "Trace")] 32 | [TestCase("/start", "Start", "Debug")] 33 | [TestCase("/stop", "Stop", "Debug")] 34 | [TestCase("/suspend", "Suspend", "Debug")] 35 | [TestCase("/Resume", "Resume", "Debug")] 36 | [TestCase("/Transfer", "Transfer", "Debug")] 37 | public async Task TestLogmessages(string route, string expectedMessageEnd, string expectedLogLevel) 38 | { 39 | await CallRoute(route); 40 | 41 | // note: the log messages end with watherver was logged thus we want to check for that 42 | Assert.That(_debugTarget.LastMessage, Does.StartWith(expectedLogLevel)); 43 | Assert.That(_debugTarget.LastMessage, Does.EndWith(expectedMessageEnd)); 44 | } 45 | 46 | 47 | [Test] 48 | public async Task NullShouldNotWrite() 49 | { 50 | var oldCounter = _debugTarget.Counter; 51 | await CallRoute("/null"); 52 | Assert.AreEqual(oldCounter, _debugTarget.Counter); 53 | } 54 | 55 | 56 | [Test] 57 | public void TestUnknownEventType() 58 | { 59 | Assert.ThrowsAsync (() => CallRoute("/invalid")); 60 | } 61 | 62 | [Test] 63 | public async Task TestWriteCoreWithEventId() 64 | { 65 | await CallRoute("/eventid"); 66 | 67 | // note: hardcoded event id = 140 in OwinTestApp.cs 68 | Assert.That(_debugTarget.LastMessage, Does.StartWith("Info")); 69 | Assert.That(_debugTarget.LastMessage, Does.Contain("EventId:140")); 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /NLog.Owin.Logging.Tests/OwinLoggerTestBase.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.Owin.Testing; 6 | using NUnit.Framework; 7 | 8 | namespace NLog.Owin.Logging.Tests 9 | { 10 | public class OwinLoggerTestBase 11 | { 12 | private TestServer _server; 13 | 14 | [OneTimeSetUp] 15 | public void StartServer() 16 | { 17 | _server = TestServer.Create(); 18 | } 19 | 20 | [OneTimeTearDown] 21 | public void StopServer() 22 | { 23 | _server.Dispose(); 24 | } 25 | 26 | protected async Task CallRoute(string route) 27 | { 28 | var result = await _server.CreateRequest(route).GetAsync(); 29 | result.EnsureSuccessStatusCode(); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /NLog.Owin.Logging.Tests/OwinTestApp.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Owin; 2 | using Microsoft.Owin.Logging; 3 | using Owin; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Diagnostics; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace NLog.Owin.Logging.Tests 12 | { 13 | /// 14 | /// This owin middleware does log messages matching the called route: 15 | /// 16 | /// /critical => "critical" 17 | /// /error => "error" 18 | /// /warning => "warning" 19 | /// /information => "information" 20 | /// /verbose => "verbose" 21 | /// 22 | /// Calling these routes allows us to check the function of the 23 | /// registered OWIN logger factory 24 | /// 25 | public class TestMiddleware : OwinMiddleware 26 | { 27 | private readonly Microsoft.Owin.Logging.ILogger _logger; 28 | 29 | public TestMiddleware(OwinMiddleware next, IAppBuilder app) : base(next) 30 | { 31 | _logger = app.CreateLogger(); 32 | } 33 | 34 | public override async Task Invoke(IOwinContext context) 35 | { 36 | var path = context.Request.Path.Value; 37 | switch (path) 38 | { 39 | case "/critical": 40 | _logger.WriteCritical("critical"); ; 41 | break; 42 | case "/error": 43 | _logger.WriteError("error"); 44 | break; 45 | case "/warning": 46 | _logger.WriteWarning("warning"); 47 | break; 48 | case "/information": 49 | _logger.WriteInformation("information"); 50 | break; 51 | case "/verbose": 52 | _logger.WriteVerbose("verbose"); 53 | break; 54 | case "/eventid": 55 | _logger.WriteCore(TraceEventType.Information, 140, "test", null, (message, error) => (string)message); 56 | break; 57 | case "/invalid": 58 | { 59 | //write invalid TraceEventType 60 | TraceEventType wrongType = (TraceEventType) (-100); 61 | WriteCore(wrongType); 62 | break; 63 | } 64 | case "/null": 65 | { 66 | //write null 67 | _logger.WriteVerbose(null); 68 | break; 69 | } 70 | case "": 71 | { 72 | //nothing 73 | break; 74 | } 75 | default: 76 | TraceEventType traceEventType; 77 | if (Enum.TryParse(path.Substring(1), true, out traceEventType)) 78 | { 79 | WriteCore(traceEventType); 80 | } 81 | break; 82 | 83 | } 84 | 85 | await context.Response.WriteAsync("Cool!"); 86 | } 87 | 88 | /// 89 | /// Write this traceEventType with to-stringed as message 90 | /// 91 | /// 92 | /// 93 | private bool WriteCore(TraceEventType traceEventType) 94 | { 95 | 96 | return _logger.WriteCore(traceEventType, 10, traceEventType.ToString(), null, (o, exception) => o.ToString()); 97 | } 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /NLog.Owin.Logging.Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar 6 | // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von 7 | // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. 8 | [assembly: ComVisible(false)] 9 | 10 | // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird 11 | [assembly: Guid("4d03a7bf-de74-47e4-b0d4-bd278696a49a")] 12 | -------------------------------------------------------------------------------- /NLog.Owin.Logging.Tests/StartupStandard.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using NUnit; 6 | using Owin; 7 | using Microsoft.Owin.Logging; 8 | using Microsoft.Owin; 9 | 10 | namespace NLog.Owin.Logging.Tests 11 | { 12 | public class StartupStandard 13 | { 14 | public void Configuration(IAppBuilder app) 15 | { 16 | app.UseNLog(); 17 | app.Use(app); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /NLog.Owin.Logging.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29001.49 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NLog.Owin.Logging", "NLog.Owin.Logging\NLog.Owin.Logging.csproj", "{23D1A639-99C4-4574-88CB-04E043BE055C}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{48DC1DAD-91DB-447B-B7DF-C76BC4CD3937}" 9 | ProjectSection(SolutionItems) = preProject 10 | appveyor.yml = appveyor.yml 11 | LICENSE = LICENSE 12 | README.md = README.md 13 | EndProjectSection 14 | EndProject 15 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NLog.Owin.Logging.Tests", "NLog.Owin.Logging.Tests\NLog.Owin.Logging.Tests.csproj", "{4D03A7BF-DE74-47E4-B0D4-BD278696A49A}" 16 | EndProject 17 | Global 18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 19 | Debug|Any CPU = Debug|Any CPU 20 | Release|Any CPU = Release|Any CPU 21 | EndGlobalSection 22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 23 | {23D1A639-99C4-4574-88CB-04E043BE055C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {23D1A639-99C4-4574-88CB-04E043BE055C}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {23D1A639-99C4-4574-88CB-04E043BE055C}.Release|Any CPU.ActiveCfg = Debug|Any CPU 26 | {23D1A639-99C4-4574-88CB-04E043BE055C}.Release|Any CPU.Build.0 = Debug|Any CPU 27 | {4D03A7BF-DE74-47E4-B0D4-BD278696A49A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 28 | {4D03A7BF-DE74-47E4-B0D4-BD278696A49A}.Debug|Any CPU.Build.0 = Debug|Any CPU 29 | {4D03A7BF-DE74-47E4-B0D4-BD278696A49A}.Release|Any CPU.ActiveCfg = Release|Any CPU 30 | {4D03A7BF-DE74-47E4-B0D4-BD278696A49A}.Release|Any CPU.Build.0 = Release|Any CPU 31 | EndGlobalSection 32 | GlobalSection(SolutionProperties) = preSolution 33 | HideSolutionNode = FALSE 34 | EndGlobalSection 35 | GlobalSection(ExtensibilityGlobals) = postSolution 36 | SolutionGuid = {23FD6BF1-BA85-45B0-B56D-96F6AE74B021} 37 | EndGlobalSection 38 | EndGlobal 39 | -------------------------------------------------------------------------------- /NLog.Owin.Logging/Extensions.cs: -------------------------------------------------------------------------------- 1 | namespace NLog.Owin.Logging 2 | { 3 | using global::Owin; 4 | using Microsoft.Owin.Logging; 5 | using NLog; 6 | using System; 7 | using System.Diagnostics; 8 | 9 | /// 10 | /// Extension class 11 | /// 12 | public static class NlogFactoryExtensions 13 | { 14 | /// 15 | /// Set the logger factory for this app builder to NLogFactory 16 | /// 17 | /// 18 | public static IAppBuilder UseNLog(this IAppBuilder app) 19 | { 20 | InitSetup(); 21 | app.SetLoggerFactory(new NLogFactory()); 22 | return app; 23 | } 24 | 25 | /// 26 | /// Set the logger factory for this app builder to NLogFactory 27 | /// 28 | /// 29 | /// 30 | public static IAppBuilder UseNLog(this IAppBuilder app, Func getLogLevel) 31 | { 32 | InitSetup(); 33 | app.SetLoggerFactory(new NLogFactory(getLogLevel)); 34 | return app; 35 | } 36 | 37 | private static void InitSetup() 38 | { 39 | LogManager.AddHiddenAssembly(typeof(NLogFactory).Assembly);//NLog.Owin.Logging 40 | LogManager.AddHiddenAssembly(typeof(LoggerExtensions).Assembly);//Microsoft.Owin.Logging 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /NLog.Owin.Logging/NLog.Owin.Logging.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | NLog.Owin.Logging 4 | NLog 5 | NLog.Owin.Logging 6 | NLog logging adapter for OWIN 7 | $([System.DateTime]::Now.ToString(yyyy)) 8 | Copyright © 2016-$(CurrentYear) Yannic Staudt & NLog Project - https://nlog-project.org/ 9 | 4.0 10 | net45 11 | true 12 | NLog, Yannic "Pysco68" Staudt, Julian Verdurmen 13 | N.png 14 | NLog.Owin.Logging 15 | MIT 16 | https://github.com/NLog/NLog.Owin.Logging 17 | git 18 | https://github.com/NLog/NLog.Owin.Logging.git 19 | OWIN NLog Logging 20 | true 21 | true 22 | true 23 | NLog.snk 24 | false 25 | true 26 | true 27 | 28 | - Updated to NLog v4.7.15 29 | - Updated to Microsoft.Owin v4.2.2 30 | - Enabled Deterministic build + SourceLink 31 | - Only emit EventId-property when non-zero 32 | 33 | See https://github.com/NLog/NLog.Owin.Logging for documentation of NLog intergration with OWIN. 34 | 35 | 36 | 37 | 38 | 39 | all 40 | runtime; build; native; contentfiles; analyzers; buildtransitive 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /NLog.Owin.Logging/NLog.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NLog/NLog.Owin.Logging/59c6255fe6fbdaf4123a4027dc5b9a85904f06ed/NLog.Owin.Logging/NLog.snk -------------------------------------------------------------------------------- /NLog.Owin.Logging/NLogAdapter.cs: -------------------------------------------------------------------------------- 1 | namespace NLog.Owin.Logging 2 | { 3 | using Microsoft.Owin.Logging; 4 | using NLog; 5 | using System; 6 | using System.Diagnostics; 7 | using System.Linq; 8 | 9 | /// 10 | /// The OWIN ILoggerFactory implementation for NLog 11 | /// 12 | public class NLogFactory : ILoggerFactory 13 | { 14 | private static readonly object[] EventIdMapper = Enumerable.Range(0, 1000).Select(id => (object)id).ToArray(); 15 | 16 | /// 17 | /// The log level translation function to get a NLog loglevel 18 | /// 19 | private readonly Func _getLogLevel; 20 | 21 | /// 22 | /// Create a logger factory with the default translation 23 | /// 24 | public NLogFactory() 25 | { 26 | this._getLogLevel = DefaultGetLogLevel; 27 | } 28 | 29 | /// 30 | /// Create a logger factory with a custom translation routine 31 | /// 32 | /// 33 | public NLogFactory(Func getLogLevel) 34 | { 35 | this._getLogLevel = getLogLevel; 36 | } 37 | 38 | /// 39 | /// This is the standard translation 40 | /// 41 | /// 42 | /// 43 | static LogLevel DefaultGetLogLevel(TraceEventType traceEventType) 44 | { 45 | switch (traceEventType) 46 | { 47 | case TraceEventType.Critical: 48 | return LogLevel.Fatal; 49 | case TraceEventType.Error: 50 | return LogLevel.Error; 51 | case TraceEventType.Warning: 52 | return LogLevel.Warn; 53 | case TraceEventType.Information: 54 | return LogLevel.Info; 55 | case TraceEventType.Verbose: 56 | return LogLevel.Trace; 57 | case TraceEventType.Start: 58 | return LogLevel.Debug; 59 | case TraceEventType.Stop: 60 | return LogLevel.Debug; 61 | case TraceEventType.Suspend: 62 | return LogLevel.Debug; 63 | case TraceEventType.Resume: 64 | return LogLevel.Debug; 65 | case TraceEventType.Transfer: 66 | return LogLevel.Debug; 67 | default: 68 | throw new ArgumentOutOfRangeException("traceEventType"); 69 | } 70 | } 71 | 72 | /// 73 | /// Creates a new ILogger instance of the given name. 74 | /// 75 | /// The logger context name. 76 | /// A logger instance. 77 | public Microsoft.Owin.Logging.ILogger Create(string name) 78 | { 79 | return new Logger(name, this._getLogLevel); 80 | } 81 | 82 | /// 83 | /// The wrapper arround NLog. Translates the logging levels 84 | /// 85 | private sealed class Logger : Microsoft.Owin.Logging.ILogger 86 | { 87 | private readonly Func _getLogLevel; 88 | 89 | private readonly NLog.Logger _logger; 90 | 91 | internal Logger(string name, Func getLogLevel) 92 | { 93 | this._getLogLevel = getLogLevel; 94 | this._logger = LogManager.GetLogger(name); 95 | } 96 | 97 | public bool WriteCore(TraceEventType eventType, int eventId, object state, Exception exception, Func formatter) 98 | { 99 | var level = this._getLogLevel(eventType); 100 | 101 | // According to docs http://katanaproject.codeplex.com/SourceControl/latest#src/Microsoft.Owin/Logging/ILogger.cs 102 | // "To check IsEnabled call WriteCore with only TraceEventType and check the return value, no event will be written." 103 | if (state is null) 104 | { 105 | return this._logger.IsEnabled(level); 106 | } 107 | if (!this._logger.IsEnabled(level)) 108 | { 109 | return false; 110 | } 111 | 112 | var logEvent = LogEventInfo.Create(level, _logger.Name, exception, (IFormatProvider)null, formatter(state, exception)); 113 | if (eventId != 0) 114 | { 115 | logEvent.Properties["EventId"] = GetEventId(eventId); 116 | } 117 | 118 | _logger.Log(typeof(Microsoft.Owin.Logging.ILogger), logEvent); 119 | return true; 120 | } 121 | 122 | private static object GetEventId(int eventId) 123 | { 124 | if (eventId > 0 && eventId < EventIdMapper.Length) 125 | return EventIdMapper[eventId]; 126 | else 127 | return eventId; 128 | } 129 | } 130 | } 131 | } -------------------------------------------------------------------------------- /NLog.Owin.Logging/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // Setting ComVisible to false makes the types in this assembly not visible 6 | // to COM components. If you need to access a type in this assembly from 7 | // COM, set the ComVisible attribute to true on that type. 8 | [assembly: ComVisible(false)] 9 | 10 | // The following GUID is for the ID of the typelib if this project is exposed to COM 11 | [assembly:Guid("84DC71BF-9C34-4801-ADA5-2E01BB0B63B2")] 12 | -------------------------------------------------------------------------------- /NLog.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/NLog/NLog.Owin.Logging/59c6255fe6fbdaf4123a4027dc5b9a85904f06ed/NLog.snk -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NLog.Owin.Logging 2 | 3 | [![Build status](https://ci.appveyor.com/api/projects/status/25xa6el222x7fhwe/branch/master?svg=true)](https://ci.appveyor.com/project/nlog/nlog-owin-logging/branch/master) 4 | [![codecov.io](https://codecov.io/github/NLog/NLog.Owin.Logging/coverage.svg?branch=master)](https://codecov.io/github/NLog/NLog.Owin.Logging?branch=master) 5 | [![Version](https://badge.fury.io/nu/NLog.Owin.Logging.svg)](https://www.nuget.org/packages/NLog.Owin.Logging) 6 | 7 | NLog logging adapter for OWIN! 8 | 9 | ## Installation 10 | 11 | There's a nuget package you can install this way: 12 | 13 | > Install-Package NLog.Owin.Logging 14 | 15 | ## Using 16 | 17 | To use the NLogAdapter with its default configuration: 18 | 19 | ```C# 20 | using NLog.Owin.Logging; 21 | 22 | public class Startup 23 | { 24 | public void Configuration(IAppBuilder app) 25 | { 26 | app.UseNLog(); 27 | } 28 | } 29 | ``` 30 | 31 | The default translation table is: 32 | 33 | | TraceEventType | NLog Loglevel | 34 | |-------------------|---------------| 35 | | Critical | Fatal | 36 | | Error | Error | 37 | | Warning | Warn | 38 | | Information | Info | 39 | | Verbose | Trace | 40 | | Start | Debug | 41 | | Stop | Debug | 42 | | Suspend | Debug | 43 | | Resume | Debug | 44 | | Transfer | Debug | 45 | 46 | If you'd like to customize this translation table you can supply a `Func` to the extension above. 47 | 48 | ```C# 49 | using NLog.Owin.Logging; 50 | using NLog; 51 | using System.Diagnostics; 52 | 53 | public class Startup 54 | { 55 | public void Configuration(IAppBuilder app) 56 | { 57 | // make a warning out of every log message! 58 | app.UseNLog((eventType) => LogLevel.Warn); 59 | } 60 | } 61 | ``` 62 | 63 | ## Note / Information 64 | 65 | (Added in version 1.1) 66 | Any `EventId` passed to this `Microsoft.Owin.Logging.ILogger.WriteCore()` implementation is passed down to NLog in the log event's properties, and can be written to output by adding the matching line in the Log appender layout: 67 | 68 | ``` 69 | ${event-properties:item=EventId} 70 | ``` 71 | 72 | You can find more information about this topic in: https://github.com/NLog/NLog/wiki/EventProperties-Layout-Renderer 73 | 74 | ## Help / Contribution 75 | 76 | If you found a bug, please create an issue. Want to contribute? Create a pull request! 77 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | image: Visual Studio 2022 2 | version: 4.0.0.{build} 3 | clone_folder: c:\projects\nlog 4 | configuration: Release 5 | platform: Any CPU 6 | dotnet_csproj: 7 | patch: true 8 | file: '**\*.csproj' 9 | assembly_version: '4.0.0' #only change on major releases 10 | file_version: '{version}' 11 | package_version: '4.0' 12 | informational_version: '4.0' 13 | version: '4.0' 14 | skip_tags: true 15 | nuget: 16 | disable_publish_on_pr: true 17 | build_script: 18 | - ps: dotnet restore 19 | - ps: msbuild /t:build,pack /p:Configuration=Release /p:IncludeSymbols=true /p:SymbolPackageFormat=snupkg /verbosity:minimal /p:ContinuousIntegrationBuild=true 20 | test_script: 21 | - nuget.exe install OpenCover -ExcludeVersion 22 | - OpenCover\tools\OpenCover.Console.exe -register:user -target:"nunit3-console.exe" -targetargs:"c:\projects\nlog\NLog.Owin.Logging.Tests\bin\Release\net452\NLog.Owin.Logging.Tests.dll" -returntargetcode -filter:"+[NLog.Owin.Logging]*" -excludebyattribute:*.ExcludeFromCodeCoverage* -hideskipped:All -output:coverage.xml 23 | - "SET PATH=C:\\Python34;C:\\Python34\\Scripts;%PATH%" 24 | - pip install codecov 25 | - codecov -f "coverage.xml" 26 | 27 | artifacts: 28 | - path: '**\NLog.*.nupkg' 29 | - path: '**\NLog.*.snupkg' 30 | deploy: 31 | - provider: NuGet 32 | api_key: 33 | secure: e+0IpLU3V1eXUsWCRjKGuyyeuLQYfFpv6BAoIihFQryuYZsOWVvxUBvQOC0dOL2n 34 | on: 35 | branch: master 36 | --------------------------------------------------------------------------------