项目作者: cmpattanayak

项目描述 :
Splunk Logging with NLog from ASP.NET Core (v3.1) API
高级语言: C#
项目地址: git://github.com/cmpattanayak/SplunkLoggingWithNLog.git
创建时间: 2020-09-11T14:11:37Z
项目社区:https://github.com/cmpattanayak/SplunkLoggingWithNLog

开源协议:

下载


SplunkLoggingWithNLog

Splunk Logging with NLog from ASP.NET Core (v3.1) API

Required Nuget Packages

  • NLog
  • NLog.Web.AspNetCore

Notes

Usually, We may not need to configure the NLog programatically (C#) as we have all the options available in nlog.config. But this example also illustrates how to programatically configure NLog. See below code.

  1. //Get nlog.config file
  2. var nlogConfiguration = NLog.LogManager.Configuration;
  3. //To ignore Splunk certificate errors
  4. ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
  5. var webServiceTarget = nlogConfiguration.FindTargetByName<WebServiceTarget>("Splunk");
  6. webServiceTarget.Url = new Uri(Configuration["SplunkUrl"]);
  7. MethodCallParameter headerParameter = new MethodCallParameter
  8. {
  9. Name = Configuration["SplunkHeaderName"],
  10. Layout = Configuration["SplunkHeaderLayout"]
  11. };
  12. webServiceTarget.Headers.Add(headerParameter);
  13. if (!String.IsNullOrWhiteSpace(AppEnvironment) && AppEnvironment.Equals("local"))
  14. {
  15. var logconsole = new ConsoleTarget("logconsole");
  16. nlogConfiguration.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole);
  17. }
  18. NLog.LogManager.Configuration = nlogConfiguration;
  19. //Set Global Diagnostics context
  20. GlobalDiagnosticsContext.Set("application", Configuration["Application"]);
  21. GlobalDiagnosticsContext.Set("environment", AppEnvironment);

Important Tip

If we do not Flush LogManager, we may not be able to log all events properly and sometime we may end up logging nothing. So, it is very important to Flush the NLog LogManager after use.

  1. NLog.LogManager.Shutdown();