Esempio n. 1
0
        public void JsonLayoutRenderingEscapeUnicode()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                {
                    new JsonAttribute("logger",  "${logger}")
                    {
                        EscapeUnicode = true
                    },
                    new JsonAttribute("level",   "${level}"),
                    new JsonAttribute("message", "${event-properties:msg}")
                    {
                        EscapeUnicode = false
                    },
                },
                SuppressSpaces       = true,
                IncludeAllProperties = true,
            };

            var logEventInfo = LogEventInfo.Create(LogLevel.Info, "\u00a9", null, "{$a}", new object[] { "\\" });

            logEventInfo.Properties["msg"] = "\u00a9";
            Assert.Equal("{\"logger\":\"\\u00a9\",\"level\":\"Info\",\"message\":\"\u00a9\",\"a\":\"\\\\\",\"msg\":\"\u00a9\"}", jsonLayout.Render(logEventInfo));
        }
Esempio n. 2
0
        public static (ILoggerProvider LogggerProvider, LogFactory LogFactory) CreateNLogProvider()
        {
            LoggingConfiguration Config = new LoggingConfiguration();

            JsonLayout Layout = new JsonLayout
            {
                IncludeAllProperties = true
            };

            Layout.Attributes.Add(new JsonAttribute("time", "${longdate}"));
            Layout.Attributes.Add(new JsonAttribute("threadId", "${threadid}"));
            Layout.Attributes.Add(new JsonAttribute("level", "${level:upperCase=true}"));
            Layout.Attributes.Add(new JsonAttribute("message", "${message}"));

            Target Target = new ConsoleTarget("Console")
            {
                Layout    = Layout,
                AutoFlush = true,                          // Matches Serilog Buffered
            };

            Config.AddTarget("Console", Target);

            Config.AddRuleForAllLevels(Target, "*", true);

            LogFactory LogFactory = new LogFactory(Config);

            NLogLoggerProvider Provider = new NLogLoggerProvider(
                new NLogProviderOptions
            {
                ShutdownOnDispose = true
            },
                LogFactory);

            return(Provider, LogFactory);
        }
Esempio n. 3
0
        /// <summary>
        /// Creates a log layout.
        /// </summary>
        /// <returns>
        /// Returns a json layout that will be used to render logs.
        /// </returns>
        private JsonLayout CreateLayout()
        {
            var jsonLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("timestamp",       "${longdate}"),
                    new JsonAttribute("level",           "${level:upperCase=true}"),
                    new JsonAttribute("message",         "${message}"),
                    new JsonAttribute("exception",       new JsonLayout
                    {
                        Attributes =
                        {
                            new JsonAttribute("type",    "${exception:format=Type}"),
                            new JsonAttribute("message", ExceptionLayout),
                        },
                        RenderEmptyObject = false
                    },
                                      false)
                }
            };

            if (Properties.Any())
            {
                var propertyLayout = new JsonLayout();
                foreach (var prop in Properties)
                {
                    propertyLayout.Attributes.Add(new JsonAttribute(prop.Name, prop.Value));
                }
                jsonLayout.Attributes.Add(new JsonAttribute("properties", propertyLayout, false));
            }

            return(jsonLayout);
        }
Esempio n. 4
0
        public void NestedJsonAttrTest()
        {
            var jsonLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("type",            "${exception:format=Type}"),
                    new JsonAttribute("message",         "${exception:format=Message}"),
                    new JsonAttribute("innerException",  new JsonLayout
                    {
                        Attributes =
                        {
                            new JsonAttribute("type",    "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                            new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                        }
                    },
                                      //don't escape layout
                                      false)
                }
            };

            var logEventInfo = new LogEventInfo
            {
                Exception = new NLogRuntimeException("test", new NullReferenceException("null is bad!"))
            };

            var json = jsonLayout.Render(logEventInfo);

            Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\", \"innerException\": { \"type\": \"System.NullReferenceException\", \"message\": \"null is bad!\" } }", json);
        }
Esempio n. 5
0
        public void ExcludeEmptyJsonProperties()
        {
            var jsonLayout = new JsonLayout()
            {
                IncludeAllProperties   = true,
                ExcludeEmptyProperties = true
            };

            jsonLayout.ExcludeProperties.Add("Excluded1");
            jsonLayout.ExcludeProperties.Add("Excluded2");

            var logEventInfo = CreateLogEventWithExcluded();

            logEventInfo.Properties.Add("EmptyProp", "");
            logEventInfo.Properties.Add("EmptyProp1", null);
            logEventInfo.Properties.Add("EmptyProp2", new DummyContextLogger()
            {
                Value = null
            });
            logEventInfo.Properties.Add("EmptyProp3", new DummyContextLogger()
            {
                Value = ""
            });
            logEventInfo.Properties.Add("NoEmptyProp4", new DummyContextLogger()
            {
                Value = "hello"
            });

            Assert.Equal(ExpectedExcludeEmptyPropertiesWithExcludes, jsonLayout.Render(logEventInfo));
        }
Esempio n. 6
0
        public void NestedJsonAttrRendersEmptyLiteralIfRenderEmptyObjectIsTrueTest()
        {
            var jsonLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("type",            "${exception:format=Type}"),
                    new JsonAttribute("message",         "${exception:format=Message}"),
                    new JsonAttribute("innerException",  new JsonLayout
                    {
                        Attributes =
                        {
                            new JsonAttribute("type",    "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                            new JsonAttribute("message", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                        },
                        RenderEmptyObject = true
                    },
                                      //don't escape layout
                                      false)
                }
            };

            var logEventInfo = new LogEventInfo
            {
                Exception = new NLogRuntimeException("test", (Exception)null)
            };

            var json = jsonLayout.Render(logEventInfo);

            Assert.Equal("{ \"type\": \"NLog.NLogRuntimeException\", \"message\": \"test\", \"innerException\": {  } }", json);
        }
Esempio n. 7
0
        public void JsonLayoutRenderingEscapeUnicode()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                {
                    new JsonAttribute("logger",  "${logger}")
                    {
                        EscapeUnicode = true
                    },
                    new JsonAttribute("level",   "${level}"),
                    new JsonAttribute("message", "${message}")
                    {
                        EscapeUnicode = false
                    },
                },
                SuppressSpaces = true
            };

            var logEventInfo = new LogEventInfo
            {
                LoggerName = "\u00a9",
                Level      = LogLevel.Info,
                Message    = "\u00a9",
            };

            Assert.Equal("{\"logger\":\"\\u00a9\",\"level\":\"Info\",\"message\":\"\u00a9\"}", jsonLayout.Render(logEventInfo));
        }
Esempio n. 8
0
        public static ILoggerProvider CreateNLogProvider()
        {
            LoggingConfiguration Config = new LoggingConfiguration();

            JsonLayout Layout = new JsonLayout
            {
                IncludeAllProperties = true
            };

            Layout.Attributes.Add(new JsonAttribute("time", "${longdate}"));
            Layout.Attributes.Add(new JsonAttribute("threadId", "${threadid}"));
            Layout.Attributes.Add(new JsonAttribute("level", "${level:upperCase=true}"));
            Layout.Attributes.Add(new JsonAttribute("message", "${message}"));

            Target Target = new FileTarget("File")
            {
                FileName = "C:\\LogsPerf\\NLog\\nlog-${shortdate}.log",
                Layout   = Layout
            };

            Config.AddTarget("File", Target);

            Config.AddRuleForAllLevels(Target, "*", true);

            NLogLoggerProvider Provider = new NLogLoggerProvider(
                new NLogProviderOptions
            {
                ShutdownOnDispose = true
            },
                new LogFactory(Config));

            return(Provider);
        }
Esempio n. 9
0
        public void IncludeAllJsonProperties()
        {
            var jsonLayout = new JsonLayout()
            {
                IncludeAllProperties = true
            };

            jsonLayout.ExcludedProperties.Add("Excluded");

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level     = LogLevel.Info,
                Message   = "hello, world"
            };

            logEventInfo.Properties.Add("StringProp", "ValueA");
            logEventInfo.Properties.Add("IntProp", 123);
            logEventInfo.Properties.Add("DoubleProp", 123.123);
            logEventInfo.Properties.Add("DecimalProp", 123.123m);
            logEventInfo.Properties.Add("BoolProp", true);
            logEventInfo.Properties.Add("NullProp", null);
            logEventInfo.Properties.Add("Excluded", "ExcludedValue");

            Assert.Equal("{ \"StringProp\": \"ValueA\", \"IntProp\": 123, \"DoubleProp\": 123.123, \"DecimalProp\": 123.123, \"BoolProp\": True, \"NullProp\": null }", jsonLayout.Render(logEventInfo));
        }
Esempio n. 10
0
        public void InitTargetFile(Session session)
        {
            //string dataTime = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");


            //":" in Path is not possible by windows
            // _filePath = _homeDir + "\\" +"LoggingData" + @"\${date:format=dd-MM-yyyy HH\:mm\:ss}.json";

            /*
             * Set and hold the file Path by every runing
             */

            var filePath = Path.Combine(_homeDir, "LoggingData", session.Name + ".json");
            var logfile  = new NLog.Targets.FileTarget("JsonLogger");


            //set the layout of json format, MaxRecursionLimit can make sub object serialized, too!!!
            var jsonLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("session",         session.Name),
                    new JsonAttribute("time",            "${longdate}"),
                    new JsonAttribute("level",           "${level:upperCase=true}"),
                    new JsonAttribute("message",         "${message}"),
                    new JsonAttribute("eventProperties", new JsonLayout
                    {
                        IncludeAllProperties = true,
                        MaxRecursionLimit    = 10
                    },                                   false)
                }
            };

            // set the attribute of the new target
            logfile.Name     = "JsonLogger";
            logfile.FileName = filePath;
            logfile.Layout   = jsonLayout;


            // add the new target to current configuration
            NLog.LogManager.Configuration.AddTarget(logfile);

            // create new rule
            var rule = new LoggingRule("JsonLogger", LogLevel.Trace, logfile);

            NLog.LogManager.Configuration.LoggingRules.Add(rule);

            /*
             * reload the new configuration. It's very important here.
             * Do not use NLog.LogManager.Configuration = config;
             * This will destory current configuration.
             * So just add and reload.
             */
            LogManager.Configuration.Reload();


            // get the specified Logger
            _logger = NLog.LogManager.GetLogger("JsonLogger");
        }
Esempio n. 11
0
        public void AttributerKeyWithQuote()
        {
            var jsonLayout = new JsonLayout();

            jsonLayout.Attributes.Add(new JsonAttribute(@"fo""o", "bar"));

            Assert.Equal(@"{ ""fo\""o"": ""bar"" }", jsonLayout.Render(LogEventInfo.CreateNullEvent()));
        }
Esempio n. 12
0
 public override string GetText(JsonLayout layout)
 {
     if (_Text == null)
     {
         _Text = Energy.Base.Json.Quote(_Value);
     }
     return(_Text);
 }
        private BaseLayout createContentLayout()
        {
            contentHolder = new LinearLayout();
            contentHolder.setSizeParams(new SizeParams(MATCH_PARENT, MATCH_PARENT));
            contentHolder.invertDirection = true;

            contentHolder.addItem(createSwitchViewLayout());

            SizeParams fityPercentWidthSizeParams = new SizeParams();

            fityPercentWidthSizeParams.WidthPercent = 50.0f;
            fityPercentWidthSizeParams.Height       = MATCH_PARENT;

            jsonInput = new LinearLayout();
            jsonInput.setSizeParams(new SizeParams(MATCH_PARENT, MATCH_PARENT));
            jsonInput.setDirection(Direction.HORIZONTAL);

            LinearLayout json1Column = new LinearLayout();

            json1Column.setSizeParams(fityPercentWidthSizeParams);
            json1Column.addItem(createJsonHeaderLayout("Left JSON"));
            EditTextLayout json1Text = new EditTextLayout();

            json1Text.edgeColor = new Color(0, 122, 204);
            json1Text.setSizeParams(new SizeParams(MATCH_PARENT, FILL));
            json1Column.addItem(json1Text);
            json1Text.susbcribeToTextChanges(() =>
            {
                model.setjson1(json1Text.getText());
            });
            json1Text.setText(Properties.Resources.TextFile1);

            LinearLayout json2Column = new LinearLayout();

            json2Column.setSizeParams(fityPercentWidthSizeParams);
            json2Column.addItem(createJsonHeaderLayout("Right JSON"));
            EditTextLayout json2Text = new EditTextLayout();

            json2Text.edgeColor = new Color(0, 122, 204);
            json2Text.setSizeParams(new SizeParams(MATCH_PARENT, FILL));
            json2Column.addItem(json2Text);
            json2Text.susbcribeToTextChanges(() =>
            {
                model.setjson2(json2Text.getText());
            });
            json2Text.setText(Properties.Resources.TextFile1);

            jsonInput.addItem(json1Column);
            jsonInput.addItem(json2Column);

            jsonResultLayout = new JsonLayout();

            contentHolder.addItem(jsonInput);

            return(contentHolder);
        }
Esempio n. 14
0
        private void AddInstanceAppenders(string fileName)
        {
            //Get the logger repository hierarchy.
            var repository = LogManager.GetRepository(Assembly.GetCallingAssembly()) as Hierarchy;

            if (repository == null)
            {
                throw new Exception("log4net repository was not configured");
            }

            #region Configure signalRAppender

            var instanceSignalRAppender = AddSignalRAppender(JobExecutionId.ToString());

            #endregion

            #region Configure file appender

            FileAppender fileAppender = null;

            if (!string.IsNullOrWhiteSpace(fileName))
            {
                fileAppender = new FileAppender
                {
                    Name           = Name + "FileAppender_" + JobExecutionId,
                    File           = fileName,
                    AppendToFile   = false,
                    Threshold      = Level.All,
                    LockingModel   = new FileAppender.MinimalLock(),
                    ImmediateFlush = true
                };

                var jsonLayout = new JsonLayout();
                jsonLayout.ActivateOptions();
                fileAppender.Layout = jsonLayout;

                fileAppender.ActivateOptions();

                _logger.AddAppender(fileAppender);
            }

            #endregion

            if (repository.GetLogger(Name) is Logger log)
            {
                log.AddAppender(instanceSignalRAppender);
                if (fileAppender != null)
                {
                    log.AddAppender(fileAppender);
                }
            }

            // Mark repository as configured and notify that is has changed.
            repository.Configured = true;
            repository.RaiseConfigurationChanged(EventArgs.Empty);
        }
Esempio n. 15
0
        private static void SetupSemaTextLogging()
        {
            try
            {
                LoggingConfiguration config   = LogManager.Configuration;
                SyslogTarget         sematext = new SyslogTarget
                {
                    MessageCreation =
                    {
                        Rfc5424     =
                        {
                            AppName = "0dcb3012-fa85-47c5-b6ca-cfd33609ac33"
                        }
                    },
                    MessageSend =
                    {
                        Protocol = ProtocolType.Tcp,
                        Tcp      = { Server = "logsene-syslog-receiver.sematext.com", Port = 514 }
                    }
                };

                config.AddTarget("sema", sematext);
                JsonLayout jsonLayout = new JsonLayout
                {
                    Attributes =
                    {
                        new JsonAttribute("exceptionType",        "${exception:format=Type}"),
                        new JsonAttribute("exceptionDetails",     "${exception:format=toString,Data}"),
                        new JsonAttribute("details",              "${message}"),
                        new JsonAttribute("exceptionMessage",     "${exception:format=Message}"),
                        new JsonAttribute("level",                "${level:uppercase=true}"),
                        new JsonAttribute("appVersion",           Helpers.DisplayVersion),
                        new JsonAttribute("innerException",       new JsonLayout
                        {
                            Attributes =
                            {
                                new JsonAttribute("type",         "${exception:format=:innerFormat=Type:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}"),
                                new JsonAttribute("innerMessage", "${exception:format=:innerFormat=Message:MaxInnerExceptionLevel=1:InnerExceptionSeparator=}")
                            }
                        },
                                          //don't escape layout
                                          false)
                    }
                };
                sematext.Layout = jsonLayout;

                LoggingRule semaRule = new LoggingRule("*", LogLevel.Warn, sematext);
                config.LoggingRules.Add(semaRule);
                LogManager.Configuration = config;
            }
            catch
            {
                Logger.Error("Failed to setup logging with sema");
            }
        }
Esempio n. 16
0
        public void GettingAttributeLayoutReturnsOriginalLayoutText()
        {
            const string originalText = "${message}";
            var          jsonLayout   = new JsonLayout();

            jsonLayout.Attributes.Add(new JsonAttribute("property", originalText));

            string attributeLayout = jsonLayout.GetAttributeLayout("property");

            attributeLayout.Should().Be(originalText);
        }
Esempio n. 17
0
        public static RedisTarget CreateRedisTarget(IConnectionMultiplexer connectionMultiplexer, int db)
        {
            var redisConnectionManager = new RedisConnectionManager(connectionMultiplexer, db);

            var exceptionLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("type",       "${exception:format=Type}"),
                    new JsonAttribute("message",    "${exception:format=Message}"),
                    new JsonAttribute("method",     "${exception:format=Method}"),
                    new JsonAttribute("stackTrace", "${exception:format=StackTrace}"),
                    new JsonAttribute("data",       "${exception:format=Data}")
                }
            };

            var requestLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("httpUrl",       "${aspnet-request:HTTP_URL}"),
                    new JsonAttribute("httpHost",      "${aspnet-request:HTTP_HOST}"),
                    new JsonAttribute("serverName",    "${aspnet-request:SERVER_NAME}"),
                    new JsonAttribute("httpUserAgent", "${aspnet-request:HTTP_USER_AGENT}"),
                    new JsonAttribute("httpVersion",   "${aspnet-request:HTTP_VERSION}"),
                    new JsonAttribute("https",         "${aspnet-request:HTTPS}"),
                    new JsonAttribute("httpMethod",    "${aspnet-request:HTTP_METHOD}"),
                    new JsonAttribute("queryString",   "${aspnet-request:QUERY_STRING}"),
                    new JsonAttribute("remoteAddress", "${aspnet-request:REMOTE_ADDR}"),
                    new JsonAttribute("user",          "${aspnet-user-identity}")
                }
            };

            var layout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("time",      "${date:universalTime=true:format=yyyy-MM-ddTHH\\:mm\\:ss.fff}"),
                    new JsonAttribute("level",     "${uppercase:${level}}"),
                    new JsonAttribute("message",   "${message}"),
                    new JsonAttribute("exception", exceptionLayout,                                                 false),
                    new JsonAttribute("request",   requestLayout,                                                   false)
                }
            };

            return(new RedisTarget(redisConnectionManager)
            {
                Name = "redis",
                DataType = "list",
                Layout = layout,
                Key = "log",
            });
        }
Esempio n. 18
0
        public void PropertyKeyWithQuote()
        {
            var jsonLayout = new JsonLayout()
            {
                IncludeAllProperties = true,
            };

            var logEventInfo = new LogEventInfo();

            logEventInfo.Properties.Add(@"fo""o", "bar");
            Assert.Equal(@"{ ""fo\""o"": ""bar"" }", jsonLayout.Render(logEventInfo));
        }
Esempio n. 19
0
        public void IncludeAllJsonProperties()
        {
            var jsonLayout = new JsonLayout()
            {
                IncludeAllProperties = true
            };

            jsonLayout.ExcludeProperties.Add("Excluded1");
            jsonLayout.ExcludeProperties.Add("Excluded2");

            var logEventInfo = CreateLogEventWithExcluded();

            Assert.Equal(ExpectedIncludeAllPropertiesWithExcludes, jsonLayout.Render(logEventInfo));
        }
Esempio n. 20
0
        private static void ConfigureLogger()
        {
            string appLogFile = Helpers.Resource.Get <string>("BRAND_LOGFILE_NAME", "application.log");

            appLogFile = appLogFile.Replace(" ", string.Empty);

            string brandID = Helpers.Resource.Get <string>("BRAND_NAME", "WLSDK");

            brandID = brandID.Replace(" ", string.Empty);

            LoggingConfiguration loggingConfiguration = LogManager.Configuration ?? new LoggingConfiguration();

            string appdata     = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create);
            string logLocation = Path.Combine(appdata, brandID, "Logs", appLogFile);

            FileTarget fileTarget = new FileTarget();

            fileTarget.FileName        = logLocation;
            fileTarget.LineEnding      = LineEndingMode.CRLF;
            fileTarget.ArchiveEvery    = FileArchivePeriod.Day;
            fileTarget.Header          = $"================= {((AssemblyTitleAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyTitleAttribute), false)).Title} =================";
            fileTarget.MaxArchiveFiles = 2;
            var jsonLayout = new JsonLayout
            {
                Attributes =
                {
                    new JsonAttribute("timestamp", @"${date:format=yyyy\-MM\-dd\THH\:mm\:ss\.fffK}"),
                    new JsonAttribute("level",     @"${level:uppercase=true}"),
                    new JsonAttribute("logClass",  @"${logger:shortName=True}"),
                    new JsonAttribute("message",   @"${message}"),
                    new JsonAttribute("exception", @"${exception:format = toString,Data: maxInnerExceptionLevel = 10}"),
                }
            };

            fileTarget.Layout = jsonLayout;

            loggingConfiguration.AddTarget(brandID + "_filelog", fileTarget);
            loggingConfiguration.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget, "WL::*");

            DebuggerTarget debugTarget = new DebuggerTarget();

            debugTarget.Layout = @"${date:format=HH\:mm\:ss\.fff} - [${logger:shortName=True}] - ${message}";

            loggingConfiguration.AddTarget(brandID + "_debuglog", debugTarget);
            loggingConfiguration.AddRule(LogLevel.Debug, LogLevel.Fatal, debugTarget, "WL::*");

            LogManager.Configuration = loggingConfiguration;
        }
Esempio n. 21
0
        public LogItemJsonConverter(JsonLayout layout)
        {
            _layout = layout;

            var regex = new Regex(@"\${(\w+):?[\w\d=@]*}");

            foreach (var attribute in _layout.Attributes)
            {
                if (attribute.Layout is SimpleLayout simpleLayout)
                {
                    var text = simpleLayout.Text;
                    var type = regex.Match(text).Groups[1].Value;
                    _fieldNames.Add(type, attribute.Name);
                }
            }
        }
        public static ISetupBuilder ConfigDefaultLogging(this ISetupBuilder loggerConfiguration, string applicationName, bool noFile = false)
        {
            loggerConfiguration = loggerConfiguration.SetupExtensions(e => e.RegisterLayoutRenderer("event-type", typeof(EventTypeLayoutRenderer)));

            if (!noFile)
            {
                const string defaultFile = "default-file";
                loggerConfiguration =
                    loggerConfiguration.LoadConfiguration(b =>
                {
                    b.Configuration.AddTarget(new AsyncTargetWrapper(new FileTarget("actual-" + defaultFile)
                    {
                        Layout = new JsonLayout
                        {
                            Attributes =
                            {
                                new JsonAttribute("time",        "${longdate}"),
                                new JsonAttribute("level",       "${level:upperCase=true}"),
                                new JsonAttribute("application", applicationName),
                                new JsonAttribute("eventType",   "${event-type}"),
                                new JsonAttribute("message",     "${message}"),
                                new JsonAttribute("Properties",
                                                  new JsonLayout
                                {
                                    ExcludeEmptyProperties = true,
                                    ExcludeProperties      = new HashSet <string>
                                    {
                                        "time",
                                        "level",
                                        "eventType",
                                        "message"
                                    },
                                    IncludeAllProperties = true
                                })
                            }
                        },
                        ArchiveAboveSize             = 5_242_880,
                        ConcurrentWrites             = false,
                        MaxArchiveFiles              = 5,
                        FileName                     = "Logs\\Log.log",
                        ArchiveFileName              = "Logs\\Log.{###}.log",
                        ArchiveNumbering             = ArchiveNumberingMode.Rolling,
                        EnableArchiveFileCompression = true
                    })
                    {
                        Name = defaultFile
                    });
        private void AddControlOutputToCheckAgainst(string name, LoggingConfiguration config)
        {
            var layout = new JsonLayout {
                SuppressSpaces = true
            };

            foreach (var attribute in GivenControlOutputAttributes())
            {
                layout.Attributes.Add(attribute);
            }
            var target = new MemoryTarget {
                Name = "control" + name, Layout = layout
            };

            config.AddTarget(target);
            SetUpRules(target, config);
        }
Esempio n. 24
0
        // ********************************************************************

        public void DynamicLog()
        {
            // prepare the logger
            var config     = LogManager.Configuration;
            var fileTarget = new FileTarget();

            config.AddTarget("Dynamic", fileTarget);

            fileTarget.FileName        = "${basedir}/Logs/${logger}.log";
            fileTarget.ArchiveFileName = "${basedir}Logs/Archives/${logger}.{#}.zip";
            fileTarget.EnableArchiveFileCompression = true;
            fileTarget.ArchiveOldFileOnStartup      = false;
            fileTarget.DeleteOldFileOnStartup       = false;
            fileTarget.AutoFlush        = true;
            fileTarget.ArchiveEvery     = FileArchivePeriod.Day;
            fileTarget.ArchiveNumbering = ArchiveNumberingMode.Rolling;
            fileTarget.MaxArchiveFiles  = 90;
            fileTarget.ConcurrentWrites = true;
            fileTarget.KeepFileOpen     = true;

            // define JSON structure
            var jsonLayout = new JsonLayout();

            jsonLayout.IncludeAllProperties = false;
            jsonLayout.Attributes.Add(new JsonAttribute("time", "${longdate}"));
            jsonLayout.Attributes.Add(new JsonAttribute("GC0_count", "${event-properties:item=GC0_count}"));
            // annyi json attributuomot adsz hozzá amennyit csak akarsz

            fileTarget.Layout = jsonLayout;
            var rule = new LoggingRule("Dynamic", LogLevel.Info, fileTarget);

            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

            // fill the GC0_count property with value
            var logEventInfo = new LogEventInfo(LogLevel.Trace, "DynamicLog", "");

            logEventInfo.Properties["GC0_count"] = GC.CollectionCount(0);

            // create the logger, and write the JSON
            var dynamicLogger = LogManager.GetLogger("DynamicLog");

            dynamicLogger.Log(LogLevel.Info, logEventInfo);
        }
Esempio n. 25
0
        //[ClassInitialize]
        public static void Initialize(TestContext ctx)
        {
            Hierarchy     hierarchy = (Hierarchy)LogManager.GetRepository();
            TraceAppender tracer    = new TraceAppender();

            tracer.ImmediateFlush = true;

            //PatternLayout layout = new PatternLayout();
            //layout.ConversionPattern = LOG_PATTERN;
            //layout.ActivateOptions();

            JsonLayout layout = new JsonLayout();

            layout.ActivateOptions();

            tracer.Layout = layout;
            tracer.ActivateOptions();
            hierarchy.Root.AddAppender(tracer);

            HttpPostAppender appender = new HttpPostAppender()
            {
                BufferSize = 20
            };

            appender.Layout            = layout;
            appender.PostUrl           = "http://requestb.in/1euiz3m1";
            appender.LogSourceIdentity = "test";

            appender.ActivateOptions();
            hierarchy.Root.AddAppender(appender);

            //FileAppender appender = new FileAppender();
            //appender.Layout = layout;
            //appender.File = @"..\..\utest.log";
            //appender.AppendToFile = true;

            //appender.ActivateOptions();
            //hierarchy.Root.AddAppender(appender);

            hierarchy.Root.Level = Level.All;
            hierarchy.Configured = true;
        }
        internal NewRelicJsonLayout(Func <NewRelic.Api.Agent.IAgent> agentFactory) : base()
        {
            _nrAgent = new Lazy <NewRelic.Api.Agent.IAgent>(agentFactory);
            LayoutRenderer.Register <UnixTimestampLayoutRenderer>(TimestampLayoutRendererName);


            SuppressSpaces    = true;
            RenderEmptyObject = false;
            MaxRecursionLimit = 1;

            Attributes.Add(new JsonAttribute(NewRelicLoggingProperty.Timestamp.GetOutputName(), "${" + TimestampLayoutRendererName + "}", false));
            Attributes.Add(new JsonAttribute(NewRelicLoggingProperty.LogLevel.GetOutputName(), "${level:upperCase=true}", true));
            Attributes.Add(new JsonAttribute(NewRelicLoggingProperty.MessageText.GetOutputName(), "${message}", true));
            Attributes.Add(new JsonAttribute(NewRelicLoggingProperty.MessageTemplate.GetOutputName(), "${message:raw=true}"));

            // correlation
            Attributes.Add(new JsonAttribute(NewRelicLoggingProperty.ThreadId.GetOutputName(), "${threadid}", true));
            Attributes.Add(new JsonAttribute(NewRelicLoggingProperty.CorrelationId.GetOutputName(), "${ActivityId}", true));
            Attributes.Add(new JsonAttribute(NewRelicLoggingProperty.ProcessId.GetOutputName(), "${processid}", true));

            // exceptions
            Attributes.Add(new JsonAttribute(NewRelicLoggingProperty.ErrorClass.GetOutputName(), "${exception:format=Type}", true));
            Attributes.Add(new JsonAttribute(NewRelicLoggingProperty.ErrorMessage.GetOutputName(), "${exception:format=Message}", true));
            Attributes.Add(new JsonAttribute(NewRelicLoggingProperty.ErrorStack.GetOutputName(), "${exception:format=StackTrace}", true));

            //Nesting json objects like this works fine and will lead to message properties
            //that look like message.property.ErrorMessage in the UI.

            _jsonLayoutForMessageProperties = new JsonLayout()
            {
                IncludeAllProperties = true,
                IncludeMdc           = false,
                //IncludeGdc = false, // GDC not supported in NLog 4.5
                IncludeMdlc       = false,
                RenderEmptyObject = false,
                SuppressSpaces    = true,
                MaxRecursionLimit = 1, // See https://github.com/newrelic/newrelic-logenricher-dotnet/issues/43
                ExcludeProperties = ExcludeProperties
            };

            Attributes.Add(new JsonAttribute("Message Properties", _jsonLayoutForMessageProperties, false));
        }
Esempio n. 27
0
        public void JsonLayoutRenderingAndEncodingLineBreaks()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                {
                    new JsonAttribute("date",    "${longdate}"),
                    new JsonAttribute("level",   "${level}"),
                    new JsonAttribute("message", "${message}"),
                }
            };

            var ev = new LogEventInfo();

            ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56);
            ev.Level     = LogLevel.Info;
            ev.Message   = "hello,\n\r world";

            Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"hello,\\n\\r world\" }", jsonLayout.Render(ev));
        }
Esempio n. 28
0
        public static (ILoggerProvider LogggerProvider, LogFactory LogFactory) CreateNLogProvider()
        {
            LoggingConfiguration Config = new LoggingConfiguration();

            JsonLayout Layout = new JsonLayout
            {
                IncludeAllProperties = true
            };

            Layout.Attributes.Add(new JsonAttribute("time", "${longdate}"));
            Layout.Attributes.Add(new JsonAttribute("threadId", "${threadid}"));
            Layout.Attributes.Add(new JsonAttribute("level", "${level:upperCase=true}"));
            Layout.Attributes.Add(new JsonAttribute("message", "${message}"));

            Target Target = new FileTarget("File")
            {
                FileName         = $"{LogFileDirectoryPath}Log${{shortdate}}.log",
                Layout           = Layout,
                KeepFileOpen     = true,                   // Default for Serilog, but not for NLog
                ConcurrentWrites = false,                  // Matches Serilog Shared
                AutoFlush        = true,                   // Matches Serilog Buffered
                ArchiveEvery     = FileArchivePeriod.Day,
                ArchiveAboveSize = ProviderComparisonBenchmarks.LogFileMaxSizeInBytes,
                ArchiveNumbering = ArchiveNumberingMode.Sequence,
            };

            Config.AddTarget("File", Target);

            Config.AddRuleForAllLevels(Target, "*", true);

            LogFactory LogFactory = new LogFactory(Config);

            NLogLoggerProvider Provider = new NLogLoggerProvider(
                new NLogProviderOptions
            {
                ShutdownOnDispose = true
            },
                LogFactory);

            return(Provider, LogFactory);
        }
Esempio n. 29
0
        public void JsonLayoutRendering()
        {
            var jsonLayout = new JsonLayout()
            {
                Attributes =
                {
                    new JsonAttribute("date",    "${longdate}"),
                    new JsonAttribute("level",   "${level}"),
                    new JsonAttribute("message", "${message}"),
                }
            };

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level     = LogLevel.Info,
                Message   = "hello, world"
            };

            Assert.Equal("{ \"date\": \"2010-01-01 12:34:56.0000\", \"level\": \"Info\", \"message\": \"hello, world\" }", jsonLayout.Render(logEventInfo));
        }
Esempio n. 30
0
        public void SkipInvalidJsonPropertyValues()
        {
            var jsonLayout = new JsonLayout()
            {
                IncludeAllProperties = true
            };

            var logEventInfo = new LogEventInfo
            {
                TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
                Level     = LogLevel.Info,
                Message   = new System.Text.StringBuilder().Append('x', 1024 * 1024).ToString(),
            };

            var expectedValue = Guid.NewGuid();

            logEventInfo.Properties["BadObject"] = new BadObject();
            logEventInfo.Properties["RequestId"] = expectedValue;

            Assert.Equal($"{{ \"RequestId\": \"{expectedValue}\" }}", jsonLayout.Render(logEventInfo));
        }