public void InstantiateLogger() { // Die Referenz auf NLogLogger.LoggingFactory wird später via DependencyInjection // an die anderen Klassen weitergegeben --> für Test direkt instantiiert. ILogging.ILoggingFactory factory = new NLogLogger.LoggingFactory(); Assert.NotNull(factory); Assert.IsInstanceOf(typeof(NLogLogger.LoggingFactory), factory); // Logger nur noch über ILogging.ILog - Interface verwenden ILogging.ILog logger = factory.GetCurrentClassLogger(); Assert.NotNull(logger); Assert.IsInstanceOf(typeof(NLogLogger.Logger), logger); // Typisierten Logger holen, um tiefergreifende Tests zu ermöglichen; für normale // Logging-Benutzer nicht zu verwenden NLogLogger.Logger typedLogger = logger as NLogLogger.Logger; Assert.NotNull(typedLogger); Assert.AreEqual(1, typedLogger.GetAllTargets().Count); Assert.AreEqual(1, typedLogger.GetTargets <NLog.Targets.MemoryTarget>().Count); NLog.Targets.MemoryTarget memTarget = typedLogger.GetTargets <NLog.Targets.MemoryTarget>()[0]; Assert.AreEqual(this.GetType().Name, typedLogger.Name); logger.Trace("First message to log."); Assert.AreEqual(1, memTarget.Logs.Count); logger.Error("Second message to log."); Assert.AreEqual(2, memTarget.Logs.Count); memTarget.Logs.Clear(); Assert.AreEqual(0, memTarget.Logs.Count); // Logger mit dem selben Namen aber über anderen Weg muss auf das // selbe Logging-Objekt zeigen ILogging.ILog sameLogger = factory.GetLogger(this.GetType().Name); Assert.AreSame(logger, sameLogger); }
public void OnHasActivityStarted() { // Arrange System.Diagnostics.Activity.Current = null; LayoutRenderer.Register("activity", typeof(ActivityTraceLayoutRenderer)); LayoutRenderer.Register("onhasactivity", typeof(OnHasActivityTraceLayoutRendererWrapper)); var logFactory = new LogFactory(); var logConfig = new LoggingConfiguration(logFactory); var memTarget = new NLog.Targets.MemoryTarget("memory"); logConfig.AddRuleForAllLevels(memTarget); memTarget.Layout = "${message} ${onhasactivity:inner=${activity:operationName}}"; logFactory.Configuration = logConfig; var logger = logFactory.GetLogger(nameof(OnHasActivityNotActive)); // Act var activity = new System.Diagnostics.Activity("World"); try { activity.Start(); logger.Info("Hello"); // Assert Assert.NotNull(System.Diagnostics.Activity.Current); Assert.Single(memTarget.Logs); Assert.Equal("Hello World", memTarget.Logs[0]); } finally { activity.Stop(); } }
public void W3CLoggerLayoutWithContextTest() { var httpContextMock = SetupHttpAccessorWithHttpContext("nlog-project.org:80", "http", "/Test.asp", "?t=1"); var logFactory = new NLog.LogFactory().Setup().SetupExtensions(ext => ext.RegisterAssembly(typeof(NLog.Web.Layouts.W3CExtendedLogLayout).Assembly)).LoadConfiguration(builder => { var layout = new NLog.Web.Layouts.W3CExtendedLogLayout(); var headerTarget = new NLog.Targets.MemoryTarget() { Name = "Header", Layout = layout.Header }; var bodyTarget = new NLog.Targets.MemoryTarget() { Name = "Body", Layout = layout }; builder.Configuration.AddRuleForAllLevels(headerTarget); builder.Configuration.AddRuleForAllLevels(bodyTarget); }).LogFactory; var logger = logFactory.GetCurrentClassLogger(); var logEvent = new LogEventInfo(LogLevel.Info, null, "RequestLogging"); logger.Log(logEvent); string expectedFieldHeaders = "c-ip cs-username s-computername cs-method cs-uri-stem cs-uri-query sc-status sc-bytes cs-bytes time-taken cs-host cs(User-Agent)"; string expectedFieldValues = $"- - {Environment.MachineName} - /Test.asp ?t=1 200 7 42 - nlog-project.org -"; string expectedHeader = $@"#Software: Microsoft Internet Information Server{System.Environment.NewLine}#Version: 1.0{System.Environment.NewLine}#Start-Date: {logEvent.TimeStamp.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)}{System.Environment.NewLine}#Fields: date time {expectedFieldHeaders}"; string expectedBody = $@"{logEvent.TimeStamp.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture)} {expectedFieldValues}"; var header = logFactory.Configuration.FindTargetByName <NLog.Targets.MemoryTarget>("Header")?.Logs?.FirstOrDefault(); var body = logFactory.Configuration.FindTargetByName <NLog.Targets.MemoryTarget>("Body")?.Logs?.FirstOrDefault(); Assert.Equal(expectedHeader, header); Assert.Equal(expectedBody, body); }
public async Task Should_log_nsb_logs() { var config = new NLog.Config.LoggingConfiguration(); var memoryTarget = new NLog.Targets.MemoryTarget(); config.AddRuleForAllLevels(memoryTarget); LogManager.Configuration = config; NsbLogManager.UseFactory(new ExtensionsLoggerFactory(new NLogLoggerFactory())); var endpointConfiguration = new EndpointConfiguration("LoggingTests"); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); endpointConfiguration.UseTransport(new LearningTransport()); endpointConfiguration.UsePersistence <LearningPersistence>(); var endpoint = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); try { Assert.IsNotEmpty(memoryTarget.Logs); } finally { await endpoint.Stop() .ConfigureAwait(false); } }
private NLogSpy(LogFactory logFactory, string name) { this.logFactory = logFactory; this.name = $"{name}.logger"; target = new NLog.Targets.MemoryTarget($"{name}.target"); target.Layout = "${message}"; }
public static NLog.Targets.MemoryTarget CreateMemoryTargetLogger(LogLevel level) { var memLogger = new NLog.Targets.MemoryTarget(); memLogger.Layout = "${level:uppercase=true} | ${logger} | ${message}"; var rule = new NLog.Config.LoggingRule("*", level, memLogger); NLog.LogManager.Configuration.LoggingRules.Add(rule); NLog.LogManager.Configuration.Reload(); return(memLogger); }
public void TestNonSerializableSayNothing() { var runner = GetRunner <CustomBeginScopeTestRunner>(); var target = new NLog.Targets.MemoryTarget() { Layout = "${message}" }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target); runner.SayNothing().Wait(); Assert.Single(target.Logs); Assert.Equal("Nothing", target.Logs[0]); }
public void TestNonSerializableSayHello() { var runner = GetRunner <CustomBeginScopeTestRunner>(); var target = new NLog.Targets.MemoryTarget() { Layout = "${message} ${mdlc:World}. Welcome ${ndlc}" }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target); runner.SayHello().Wait(); Assert.Single(target.Logs); Assert.Equal("Hello Earth. Welcome Earth People", target.Logs[0]); }
public void TestAdapter() { var nLogCapture = new NLog.Targets.MemoryTarget(); nLogCapture.Layout = "${level}: ${message}"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(nLogCapture, NLog.LogLevel.Debug); var ourAdapter = LdNLog.Adapter; var logger1 = ourAdapter.Logger("things"); var logger2 = logger1.SubLogger("stuff"); logger1.Debug("d0"); logger1.Debug("d1,{0}", "a"); logger1.Debug("d2,{0},{1}", "a", "b"); logger1.Debug("d3,{0},{1},{2}", "a", "b", "c"); logger1.Info("i0"); logger1.Info("i1,{0}", "a"); logger1.Info("i2,{0},{1}", "a", "b"); logger1.Info("i3,{0},{1},{2}", "a", "b", "c"); logger1.Warn("w0"); logger1.Warn("w1,{0}", "a"); logger1.Warn("w2,{0},{1}", "a", "b"); logger1.Warn("w3,{0},{1},{2}", "a", "b", "c"); logger1.Error("e0"); logger1.Error("e1,{0}", "a"); logger1.Error("e2,{0},{1}", "a", "b"); logger1.Error("e3,{0},{1},{2}", "a", "b", "c"); logger2.Warn("goodbye"); Assert.Collection(nLogCapture.Logs, ExpectEvent("things", LogLevel.Debug, "d0"), ExpectEvent("things", LogLevel.Debug, "d1,a"), ExpectEvent("things", LogLevel.Debug, "d2,a,b"), ExpectEvent("things", LogLevel.Debug, "d3,a,b,c"), ExpectEvent("things", LogLevel.Info, "i0"), ExpectEvent("things", LogLevel.Info, "i1,a"), ExpectEvent("things", LogLevel.Info, "i2,a,b"), ExpectEvent("things", LogLevel.Info, "i3,a,b,c"), ExpectEvent("things", LogLevel.Warn, "w0"), ExpectEvent("things", LogLevel.Warn, "w1,a"), ExpectEvent("things", LogLevel.Warn, "w2,a,b"), ExpectEvent("things", LogLevel.Warn, "w3,a,b,c"), ExpectEvent("things", LogLevel.Error, "e0"), ExpectEvent("things", LogLevel.Error, "e1,a"), ExpectEvent("things", LogLevel.Error, "e2,a,b"), ExpectEvent("things", LogLevel.Error, "e3,a,b,c"), ExpectEvent("things.stuff", LogLevel.Warn, "goodbye") ); }
public void TestNonSerializableSayHi() { var runner = GetRunner <CustomBeginScopeTestRunner>(); var target = new NLog.Targets.MemoryTarget() { Layout = "${message} ${mdlc:World}. Welcome ${ndlc}" }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target); var scopeString = runner.SayHi().Result; Assert.Single(target.Logs); Assert.Equal("Hi Earth. Welcome Earth People", target.Logs[0]); // Assert.Equal("Earth People", scopeString); <-- Bug https://github.com/aspnet/Logging/issues/893 }
public void TestExtraMessageTemplatePropertySayHigh5() { ConfigureServiceProvider <CustomLoggerPropertyTestRunner>((s) => s.AddSingleton(typeof(ILogger <>), typeof(SameAssemblyLogger <>))); var runner = GetRunner <CustomLoggerPropertyTestRunner>(); var target = new NLog.Targets.MemoryTarget() { Layout = "${message}|${all-event-properties}" }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target); runner.SayHigh5(); Assert.Single(target.Logs); Assert.Equal(@"Hi 5|ActivityId=42", target.Logs[0]); }
public void TestNonSerializableSayHelloWithScope() { var runner = GetRunner <CustomBeginScopeTestRunner>(new NLogProviderOptions() { IncludeScopes = false }); var target = new NLog.Targets.MemoryTarget() { Layout = "${message} ${mdlc:World}. Welcome ${ndlc}" }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target); runner.SayHello().Wait(); Assert.Single(target.Logs); Assert.Equal("Hello . Welcome ", target.Logs[0]); }
public void TestCallSiteSayHello() { ConfigureServiceProvider <CustomLoggerCallSiteTestRunner>((s) => s.AddSingleton(typeof(ILogger <>), typeof(SameAssemblyLogger <>))); var runner = GetRunner <CustomLoggerCallSiteTestRunner>(); var target = new NLog.Targets.MemoryTarget() { Layout = "${callsite}|${message}" }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target); runner.SayHello(); Assert.Single(target.Logs); Assert.Contains("SayHello", target.Logs[0]); Assert.Contains("stuff", target.Logs[0]); }
public void SingleLogEventTest() { NLog.LogManager.ThrowConfigExceptions = true; NLog.LayoutRenderers.LayoutRenderer.Register("AzureAccessToken", typeof(AccessTokenLayoutRenderer)); var logFactory = new LogFactory(); var logConfig = new Config.LoggingConfiguration(logFactory); var memTarget = new NLog.Targets.MemoryTarget("Test") { Layout = "${AzureAccessToken:ResourceName=https\\://database.windows.net/}" }; logConfig.AddRuleForAllLevels(memTarget); logFactory.Configuration = logConfig; logFactory.GetLogger("test").Info("Hello World"); Assert.Single(memTarget.Logs); // One queue logFactory.Configuration = null; Assert.True(WaitForTokenTimersStoppedAndGarbageCollected()); }
public void Does_maintain_callsite() { try { NLog.LogManager.ThrowExceptions = true; // Only use this for unit-tests var target = new NLog.Targets.MemoryTarget(); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target); Logging.LogManager.LogFactory = new NLogger.NLogFactory(); var log = ServiceStack.Logging.LogManager.LogFactory.GetLogger(GetType()); log.InfoFormat("Message"); log.InfoFormat("Message with Args {0}", "Foo"); log.Info("Message with Exception", new Exception("Foo Exception")); Assert.AreEqual(3, target.Logs.Count); } finally { NLog.Common.InternalLogger.Reset(); NLog.LogManager.Configuration = null; } }
public void PushPropertyTest() { try { NLog.LogManager.ThrowExceptions = true; // Only use this for unit-tests var target = new NLog.Targets.MemoryTarget(); NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target); Logging.LogManager.LogFactory = new NLogger.NLogFactory(); var log = Logging.LogManager.LogFactory.GetLogger(GetType()); using (log.PushProperty("Hello", "World")) { log.InfoFormat("Message"); } Assert.AreEqual(1, target.Logs.Count); } finally { NLog.Common.InternalLogger.Reset(); NLog.LogManager.Configuration = null; } }
public GMLogger() { var config = new NLog.Config.LoggingConfiguration(); var layout = "${time} [${level:}] - ${ndc}${message}"; memoryTarget = new NLog.Targets.MemoryTarget(); memoryTarget.Layout = layout; var fileTarget = new NLog.Targets.FileTarget(); fileTarget.FileName = "gm-log.txt"; fileTarget.Layout = layout; config.AddRuleForOneLevel(LogLevel.Error, memoryTarget); config.AddRuleForOneLevel(LogLevel.Warn, memoryTarget); config.AddRuleForOneLevel(LogLevel.Info, memoryTarget); config.AddRuleForAllLevels(fileTarget); LogManager.Configuration = config; }
/// <summary> /// このクラスの新しいインスタンスを生成します。 /// </summary> public App() { this.Logger = new CompositeLogger( new DebugLogger(), new NLogger() { PublisherType = typeof(ILoggerFacadeExtension), ConfigurationFactory = () => { var headerText = new StringBuilder(); headerText.AppendLine($"# {this.ProductInfo.Product} ${{var:CTG}} Log"); headerText.AppendLine($"# {Environment.OSVersion} - CLR {Environment.Version}"); headerText.AppendLine("# ${environment:PROCESSOR_ARCHITECTURE} - ${environment:PROCESSOR_IDENTIFIER}"); headerText.AppendLine("# ${environment:COMPUTERNAME}"); headerText.Append("##"); var header = new NLog.Layouts.CsvLayout(); header.Delimiter = NLog.Layouts.CsvColumnDelimiterMode.Tab; header.Quoting = NLog.Layouts.CsvQuotingMode.Nothing; header.Columns.Add(new NLog.Layouts.CsvColumn(string.Empty, headerText.ToString())); var layout = new NLog.Layouts.CsvLayout(); layout.Delimiter = NLog.Layouts.CsvColumnDelimiterMode.Tab; layout.Quoting = NLog.Layouts.CsvQuotingMode.Nothing; layout.Header = header; layout.Columns.Add(new NLog.Layouts.CsvColumn(string.Empty, "${longdate}")); layout.Columns.Add(new NLog.Layouts.CsvColumn(string.Empty, "${environment-user}")); layout.Columns.Add(new NLog.Layouts.CsvColumn(string.Empty, $"{this.ProductInfo.Version}")); layout.Columns.Add(new NLog.Layouts.CsvColumn(string.Empty, "${processid}")); layout.Columns.Add(new NLog.Layouts.CsvColumn(string.Empty, "${threadid}")); layout.Columns.Add(new NLog.Layouts.CsvColumn(string.Empty, "${message}")); var file = new NLog.Targets.FileTarget(); file.Encoding = Encoding.UTF8; file.Footer = "${newline}"; file.FileName = "${var:DIR}/${var:CTG}.log"; file.ArchiveFileName = "${var:DIR}/archive/{#}.${var:CTG}.log"; file.ArchiveEvery = NLog.Targets.FileArchivePeriod.Day; file.ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.Date; file.MaxArchiveFiles = 10; file.Layout = layout; var memory = new NLog.Targets.MemoryTarget(); memory.Layout = layout; var config = new NLog.Config.LoggingConfiguration(); config.AddTarget(nameof(file), file); config.AddTarget(nameof(memory), memory); config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, file)); config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, memory)); config.Variables.Add("DIR", this.SharedDataStore.LogDirectoryPath); return(config); }, CreateLoggerHook = (logger, category) => { // ログの種類ごとにファイルを切り替える logger.Factory.Configuration.Variables.Add("CTG", category.ToString()); logger.Factory.ReconfigExistingLoggers(); }, }); this.ProductInfo = new ProductInfo(); this.SharedDataStore = new(this.Logger, this.ProductInfo, Process.GetCurrentProcess()); UnhandledExceptionObserver.Observe(this, this.Logger, this.ProductInfo); }
protected void OnActionRecognizeActivated(object sender, EventArgs e) { TreeIter iter, imageiter; //Создаем новый лог if (RecognizeLog == null) { NLog.Config.LoggingConfiguration config = LogManager.Configuration; RecognizeLog = new NLog.Targets.MemoryTarget(); RecognizeLog.Name = "recognizelog"; RecognizeLog.Layout = "${level} ${message}"; config.AddTarget("recognizelog", RecognizeLog); NLog.Config.LoggingRule rule = new NLog.Config.LoggingRule("*", LogLevel.Debug, RecognizeLog); config.LoggingRules.Add(rule); LogManager.Configuration = config; } else { RecognizeLog.Logs.Clear(); } logger.Info("Запущен новый процесс распознования..."); if (!ImageList.GetIterFirst(out iter)) { logger.Warn("Список изображений пуст. Остановка."); return; } logger.Info("Всего документов: {0}", ImageList.IterNChildren()); progresswork.Text = "Распознование документов..."; progresswork.Adjustment.Upper = ImageList.IterNChildren(); MainClass.WaitRedraw(); do { if (ImageList.IterDepth(iter) == 0) { logger.Info((string)ImageList.GetValue(iter, 1)); //Получаем список изображений документа int ImagesCount = ImageList.IterNChildren(iter); Pixbuf[] Images = new Pixbuf [ImagesCount]; int i = 0; ImageList.IterChildren(out imageiter, iter); do { Images [i] = (Pixbuf)ImageList.GetValue(imageiter, 5); i++; } while (ImageList.IterNext(ref imageiter)); Document doc = (Document)ImageList.GetValue(iter, 3); //Распознание QR кода с распознаванием типа документа var qrResult = QRCodeRecognizer.TryParse(Images, ref doc); //Если QR кода нет или не распознан попытка распознать другими способами if (!qrResult) { logger.Warn("QR код не распознан или не указан в документе. Пытаемся распознать другими способами..."); if (doc == null) { logger.Warn("Тип не определён. Переходим к следующему..."); continue; } if (doc.Template == null) { logger.Warn("Шаблон распознования не указан. Переходим к следующему..."); continue; } logger.Info("Тип: {0}", doc.Name); logger.Info("Количество страниц: {0}", ImagesCount); logger.Info("Инициализация движка..."); RecognizeDoc tess = new RecognizeDoc(doc, Images); tess.DiagnosticMode = checkDiagnostic.Active; //FIXME Для теста tess.parent = this; try { tess.Recognize(); } catch (Exception ex) { QSMain.ErrorMessageWithLog(this, "Ошибка в модуле распознования!", logger, ex); ShowLog(); } } else { ImageList.SetValue(iter, 7, doc.Name); ImageList.SetValue(iter, 3, doc); } ImageList.SetValue(iter, 8, GetDocIconByState(doc.State)); } progresswork.Adjustment.Value++; MainClass.WaitRedraw(); }while(ImageList.IterNext(ref iter)); logger.Info("Выполнено"); progresswork.Text = "Выполнено"; progresswork.Fraction = 0; CurrentDoc = (Document)ImageList.GetValue(CurrentDocIter, 3); UpdateFieldsWidgets(true); }
protected void OnAction1Activated(object sender, EventArgs e) { TreeIter iter, imageiter; //Создаем новый лог if (RecognizeLog == null) { NLog.Config.LoggingConfiguration config = LogManager.Configuration; RecognizeLog = new NLog.Targets.MemoryTarget(); RecognizeLog.Name = "recognizelog"; RecognizeLog.Layout = "${level} ${message}"; config.AddTarget("recognizelog", RecognizeLog); NLog.Config.LoggingRule rule = new NLog.Config.LoggingRule("*", LogLevel.Debug, RecognizeLog); config.LoggingRules.Add(rule); LogManager.Configuration = config; } else RecognizeLog.Logs.Clear(); logger.Info("Запущен новый процесс распознования..."); if(!ImageList.GetIterFirst(out iter)) { logger.Warn("Список изображений пуст. Остановка."); return; } logger.Info("Всего документов: {0}", ImageList.IterNChildren()); progresswork.Text = "Распознование документов..."; progresswork.Adjustment.Upper = ImageList.IterNChildren(); MainClass.WaitRedraw(); do { if(ImageList.IterDepth(iter) == 0) { logger.Info((string) ImageList.GetValue(iter, 1)); Document doc = (Document) ImageList.GetValue(iter, 3); if(doc == null) { logger.Warn("Тип не определён. Переходим к следующему..."); continue; } if(doc.Template == null) { logger.Warn("Шаблон распознования не указан. Переходим к следующему..."); continue; } int ImagesCount = ImageList.IterNChildren(iter); Pixbuf[] Images = new Pixbuf[ImagesCount]; int i = 0; ImageList.IterChildren(out imageiter, iter); do { Images[i] = (Pixbuf) ImageList.GetValue(imageiter, 5); i++; }while(ImageList.IterNext(ref imageiter)); logger.Info("Тип: {0}", doc.TypeName); logger.Info("Количество страниц: {0}", ImagesCount); logger.Info("Инициализация движка..."); RecognizeDoc tess = new RecognizeDoc(doc, Images); tess.DiagnosticMode = checkDiagnostic.Active; //FIXME Для теста tess.parent = this; try { tess.Recognize(); } catch (Exception ex) { QSMain.ErrorMessageWithLog (this, "Ошибка в модуле распознования!", logger, ex); ShowLog(); } ImageList.SetValue(iter, 8, GetDocIconByState(doc.State)); } progresswork.Adjustment.Value++; MainClass.WaitRedraw(); }while(ImageList.IterNext(ref iter)); logger.Info("Выполнено"); progresswork.Text = "Выполнено"; progresswork.Fraction = 0; UpdateFieldsWidgets(true); }