public void TestDurationSingleItem(string inputLayout, string expectedResult) { var logFactory = new LogFactory(); var xmlStream = new System.IO.StringReader($@"<nlog throwConfigExceptions='true'> <targets> <target name='Memory' type='Memory' layout='{inputLayout}' /> </targets> <rules> <logger name='*' writeTo='Memory' /> </rules></nlog>"); var xmlReader = System.Xml.XmlReader.Create(xmlStream); var logConfig = new NLog.Config.XmlLoggingConfiguration(xmlReader, null); logFactory.Configuration = logConfig; var memTarget = logFactory.Configuration.FindTargetByName <NLog.Targets.MemoryTarget>("Memory"); var logger = logFactory.GetCurrentClassLogger(); using (var newActivity = new System.Diagnostics.Activity("MyOperation").Start()) { var dateTime = DateTime.UtcNow.Date; newActivity.SetStartTime(dateTime); newActivity.SetEndTime(dateTime.AddHours(1).AddMinutes(2).AddSeconds(3).AddTicks(40567)); logger.Info("Hello"); Assert.Equal(expectedResult, System.Linq.Enumerable.FirstOrDefault(memTarget.Logs)); } }
private ILogger GetLogger() { var configFile = new NLog.Config.XmlLoggingConfiguration("D:\\home\\site\\wwwroot\\Nlog.config"); var factory = new NLog.LogFactory(configFile); NLogLoggerProvider provider = new NLogLoggerProvider(new NLogProviderOptions(), factory); return(provider.CreateLogger(ATFLoggerName)); }
public static ILoggerFactory AddNLog(this ILoggerFactory factory, IHostingEnvironment env) { var path = Path.Combine(env.WebRootPath, "NLog.config"); var xmlConfig = new NLog.Config.XmlLoggingConfiguration(path); var logFactory = new LogFactory(xmlConfig); return(AddNLog(factory, logFactory)); }
private void ConfigureLogging() { string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string logFileName = Path.Combine(assemblyFolder, "NLog.config"); var config = new NLog.Config.XmlLoggingConfiguration(logFileName); LogManager.Configuration = config; }
private static IStructuredLogger CreateNLogAdapter(OperationContext operationContext, DistributedCacheServiceArguments arguments) { Contract.RequiresNotNull(arguments.Configuration.LoggingSettings); // This is done for performance. See: https://github.com/NLog/NLog/wiki/performance#configure-nlog-to-not-scan-for-assemblies NLog.Config.ConfigurationItemFactory.Default = new NLog.Config.ConfigurationItemFactory(typeof(NLog.ILogger).GetTypeInfo().Assembly); // This is needed for dependency ingestion. See: https://github.com/NLog/NLog/wiki/Dependency-injection-with-NLog // The issue is that we need to construct a log, which requires access to both our config and the host. It // seems too much to put it into the AzureBlobStorageLogTarget itself, so we do it here. var defaultConstructor = NLog.Config.ConfigurationItemFactory.Default.CreateInstance; NLog.Config.ConfigurationItemFactory.Default.CreateInstance = type => { if (type == typeof(AzureBlobStorageLogTarget)) { var log = CreateAzureBlobStorageLogAsync(operationContext, arguments, arguments.Configuration.LoggingSettings.Configuration).Result; var target = new AzureBlobStorageLogTarget(log); return(target); } return(defaultConstructor(type)); }; NLog.Targets.Target.Register <AzureBlobStorageLogTarget>(nameof(AzureBlobStorageLogTarget)); // This is done in order to allow our logging configuration to access key telemetry information. var telemetryFieldsProvider = arguments.TelemetryFieldsProvider; NLog.LayoutRenderers.LayoutRenderer.Register("APEnvironment", _ => telemetryFieldsProvider.APEnvironment); NLog.LayoutRenderers.LayoutRenderer.Register("APCluster", _ => telemetryFieldsProvider.APCluster); NLog.LayoutRenderers.LayoutRenderer.Register("APMachineFunction", _ => telemetryFieldsProvider.APMachineFunction); NLog.LayoutRenderers.LayoutRenderer.Register("MachineName", _ => telemetryFieldsProvider.MachineName); NLog.LayoutRenderers.LayoutRenderer.Register("ServiceName", _ => telemetryFieldsProvider.ServiceName); NLog.LayoutRenderers.LayoutRenderer.Register("ServiceVersion", _ => telemetryFieldsProvider.ServiceVersion); NLog.LayoutRenderers.LayoutRenderer.Register("Stamp", _ => telemetryFieldsProvider.Stamp); NLog.LayoutRenderers.LayoutRenderer.Register("Ring", _ => telemetryFieldsProvider.Ring); NLog.LayoutRenderers.LayoutRenderer.Register("ConfigurationId", _ => telemetryFieldsProvider.ConfigurationId); NLog.LayoutRenderers.LayoutRenderer.Register("CacheVersion", _ => Utilities.Branding.Version); NLog.LayoutRenderers.LayoutRenderer.Register("Role", _ => GlobalInfoStorage.GetGlobalInfo(GlobalInfoKey.LocalLocationStoreRole)); NLog.LayoutRenderers.LayoutRenderer.Register("BuildId", _ => GlobalInfoStorage.GetGlobalInfo(GlobalInfoKey.BuildId)); // Follows ISO8601 without timezone specification. // See: https://kusto.azurewebsites.net/docs/query/scalar-data-types/datetime.html // See: https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings?view=netframework-4.8#the-round-trip-o-o-format-specifier var processStartTimeUtc = SystemClock.Instance.UtcNow.ToString("o", System.Globalization.CultureInfo.InvariantCulture); NLog.LayoutRenderers.LayoutRenderer.Register("ProcessStartTimeUtc", _ => processStartTimeUtc); var configuration = new NLog.Config.XmlLoggingConfiguration(arguments.Configuration.LoggingSettings.NLogConfigurationPath); return(new NLogAdapter(operationContext.TracingContext.Logger, configuration)); }
public static void Log() { string filePath = @"D:\log11.txt"; //string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //assemblyFolder = assemblyFolder.Replace("bin\\Debug",""); // NLog.LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(assemblyFolder + "\\NLog.config", true); string assemblyFolder = @" D:\Disk1\Projeler\Visual Studio 2017\Projects\SolutionTalent2.0\OnlineTalent.Log\"; var config = new NLog.Config.XmlLoggingConfiguration(assemblyFolder + "\\NLog.config", true); var logfile = new NLog.Targets.FileTarget() { FileName = filePath, Name = "logfile" }; var logconsole = new NLog.Targets.ConsoleTarget() { Name = "logconsole" }; config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logfile)); config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logconsole)); NLog.LogManager.Configuration = config; /* * var config = new NLog.Config.LoggingConfiguration(); * * var logfile = new NLog.Targets.FileTarget() { FileName = filePath, Name = "logfile" }; * //var logconsole = new NLog.Targets.ConsoleTarget() { Name = "logconsole" }; * * // config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logconsole)); * // config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logfile)); * * NLog.LogManager.Configuration = config; */ var logger = NLog.LogManager.GetCurrentClassLogger(); logger.Info("Hello World"); }
public NLogLoggerManager(IBootupConfigurationProvider bootupConfigurationProvider, IEnvironment env) { if (_initialized == false) { lock (typeof(NLogLoggerManager)) { if (_initialized != false) { return; } var configurationFilePath = bootupConfigurationProvider.GetNLogConfigFilePath(); if (configurationFilePath != null) { configurationFilePath = Path.Combine(env.ContentRootPath, configurationFilePath); if (System.IO.File.Exists(configurationFilePath)) { var config = new NLogSelf.Config.XmlLoggingConfiguration(configurationFilePath, false); NLogSelf.LogManager.Configuration = config; } } _initialized = true; } } }
//static void Main(string[] args) static void Main(string[] args) { #if (!DEBUG) #region CurrentDirectory zum Installationspfad verlegen string path = System.Reflection.Assembly.GetExecutingAssembly().Location; path = System.IO.Path.GetDirectoryName(path); System.IO.Directory.SetCurrentDirectory(path); #endregion #endif #region Service installieren/deinstallieren/debuggen if (args.Length > 0) { InternalInstallUtil installUtil = new InternalInstallUtil(); for (int i = 0; i < args.Length; i++) { switch (args[i].ToUpper()) { case "/I": { installUtil.InstallService(); return; } case "/U": { installUtil.UninstallService(); return; } case "/D": { #region NLog konfigurieren ExerciseStatisticService { NLog.Config.LoggingConfiguration configuration; NLog.Targets.ColoredConsoleTarget consoleTarget = new NLog.Targets.ColoredConsoleTarget(); consoleTarget.Name = "console"; consoleTarget.Layout = "[${level}] ${longdate}: ${callsite} ||| ${message} ${Exception}"; configuration = new NLog.Config.LoggingConfiguration(); configuration.AddTarget("console", consoleTarget); configuration.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, consoleTarget)); NLog.LogManager.Configuration = configuration; } #endregion ExerciseStatisticService service = new ExerciseStatisticService(); service.OnStart(null); Console.WriteLine("Service Started..."); Console.WriteLine("<press any key to exit...>"); while (Console.Read() == -1) { System.Threading.Thread.Sleep(100); } ; service.OnStop(); return; } default: break; } } } #endregion #region NLog konfigurieren ExerciseStatisticService { NLog.Config.LoggingConfiguration configuration; string configFile = System.IO.Path.Combine(Environment.CurrentDirectory, "ExerciseStatisticService.NLog.config"); if (System.IO.File.Exists(configFile)) { configuration = new NLog.Config.XmlLoggingConfiguration(configFile); } else { NLog.Targets.ColoredConsoleTarget consoleTarget = new NLog.Targets.ColoredConsoleTarget(); consoleTarget.Name = "console"; consoleTarget.Layout = "[${level}] ${longdate}: ${callsite} ||| ${message} ${Exception}"; configuration = new NLog.Config.LoggingConfiguration(); configuration.AddTarget("console", consoleTarget); configuration.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, consoleTarget)); } NLog.LogManager.Configuration = configuration; } #endregion // Wenn wir bis hierher kommen, dann kann der Service normal gestartet werden. ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new ExerciseStatisticService() }; ServiceBase.Run(ServicesToRun); }
private void ConfigureLogging() { string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); LogFileName = Path.Combine(assemblyFolder, "NLog.config"); var config = new NLog.Config.XmlLoggingConfiguration(LogFileName); LogManager.Configuration = config; var targets = config.AllTargets; if (targets != null && targets.Any() && targets.First() is FileTarget) { LogFileName = ((FileTarget)targets.First()).FileName.Render(new LogEventInfo()); } }
protected virtual void Initialize() { if (this.IsInitialized) return; if (this.NLogger == null) { try { string configPath = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase), "NLog.config"); if (configPath.StartsWith("file:")) configPath = configPath.Substring("file:".Length).TrimStart(Path.DirectorySeparatorChar); NLog.Config.LoggingConfiguration config = new NLog.Config.XmlLoggingConfiguration(configPath); using (var context = new NLog.Config.InstallationContext()) { config.Install(context); } this.NLogger = NLog.LogManager.GetCurrentClassLogger(); this.NLogger.Factory.Configuration = config; } catch (Exception ex) { Debug.WriteLine(ex); throw; } finally { } } this.IsInitialized = true; }
/// <summary> /// Configures the specified application. /// </summary> /// <param name="app">The application.</param> /// <param name="env">The env.</param> /// <param name="loggerFactory">The logger factory.</param> public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { var nlogConfigFile = loggerFactory.AddNLog(); var loggingConfig = new NLog.Config.XmlLoggingConfiguration(env.ContentRootPath + "/nlog.config"); var logsDir = this.Configuration.GetSection("Logging").GetValue <string>("NLogLogsDir"); if (!string.IsNullOrEmpty(logsDir)) { loggingConfig.Variables["LogDir"] = logsDir; } loggerFactory.ConfigureNLog(loggingConfig); loggerFactory.AddConsole(this.Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.All }); app.UseCors(builder => { builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); // NAME middleware should be registered first so that the header is set before any other middleware has a change to send a response app.UseNAME(config => { Assembly a = typeof(Startup).GetTypeInfo().Assembly; config.APIName = a.GetName().Name; config.APIVersion = a.GetName().Version.ToString(); config.DependenciesFilePath = env.ContentRootPath + @"/dependencies.json"; }); app.Use((context, next) => { if (context.Request.Headers.TryGetValue("X-Forwarded-Path", out StringValues values) && values.Count > 0 && !string.IsNullOrWhiteSpace(values[0])) { context.Request.PathBase = values[0]; } return(next()); }); app.UseMvc(); app.UseSwagger(action => { }); app.UseSwaggerUi(c => { Assembly a = typeof(Startup).GetTypeInfo().Assembly; c.SwaggerEndpoint("/swagger/v1/swagger.json", a.GetName().Name); c.SwaggerEndpoint("/name/swagger/v1/swagger.json", "/name Reverse proxy"); c.SupportedSubmitMethods(new string[] { "post", "get", "put", "delete", "patch", "head" }); }); }