/// <summary> /// Render layout <paramref name="layout"/> with <paramref name="logEventInfo"/> and compare result with <paramref name="expected"/>. /// </summary> protected static void AssertLayoutRendererOutput(Layout layout, LogEventInfo logEventInfo, string expected) { layout.Initialize(null); string actual = layout.Render(logEventInfo); layout.Close(); Assert.Equal(expected, actual); }
public SdParam(SdParamConfig sdParamConfig, EnforcementConfig enforcementConfig) { name = sdParamConfig.Name; value = sdParamConfig.Value; paramNamePolicySet = new ParamNamePolicySet(enforcementConfig); paramValuePolicySet = new ParamValuePolicySet(enforcementConfig); }
public static string GetMessageInner(bool useJSON, Layout layout, LogEventInfo info) { if (!useJSON) return layout.Render(info); var logLine = new LogLine { TimeStampISO8601 = info.TimeStamp.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), Message = info.FormattedMessage, Level = info.Level.Name, Type = "amqp", Source = new Uri(string.Format("nlog://{0}/{1}", HostName, info.LoggerName)) }; logLine.AddField("exception", info.Exception); if (info.Properties.Count > 0 && info.Properties.ContainsKey("fields")) foreach (var kv in (IEnumerable<KeyValuePair<string, object>>) info.Properties["fields"]) logLine.AddField(kv.Key, kv.Value); if (info.Properties.Count > 0 && info.Properties.ContainsKey("tags")) foreach (var tag in (IEnumerable<string>) info.Properties["tags"]) logLine.AddTag(tag); logLine.EnsureADT(); return JsonConvert.SerializeObject(logLine); }
private void AssertMessageAndLogLevelForTruncatedMessages(LogLevel loglevel, EventLogEntryType expectedEventLogEntryType, string expectedMessage, Layout entryTypeLayout) { const int expectedEntryCount = 1; var eventRecords = Write(loglevel, expectedEventLogEntryType, expectedMessage, entryTypeLayout, EventLogTargetOverflowAction.Truncate).ToList(); Assert.Equal(expectedEntryCount, eventRecords.Count); AssertWrittenMessage(eventRecords, expectedMessage); }
public Rfc3164(Facility facility, Rfc3164Config rfc3164Config, EnforcementConfig enforcementConfig) : base(facility, enforcementConfig) { hostnamePolicySet = new PlainHostnamePolicySet(enforcementConfig); tagPolicySet = new TagPolicySet(enforcementConfig); plainContentPolicySet = new PlainContentPolicySet(enforcementConfig); asciiMessagePolicy = new AsciiMessagePolicy(enforcementConfig); hostnameLayout = rfc3164Config.Hostname; tagLayout = rfc3164Config.Tag; }
public AsyncLogger(Layout loggingLayout, EnforcementConfig enforcementConfig, MessageBuilder messageBuilder, MessageTransmitterConfig messageTransmitterConfig) { layout = loggingLayout; cts = new CancellationTokenSource(); token = cts.Token; throttling = Throttling.FromConfig(enforcementConfig.Throttling); queue = NewBlockingCollection(); buffer = new ByteArray(enforcementConfig.TruncateMessageTo); messageTransmitter = MessageTransmitter.FromConfig(messageTransmitterConfig); Task.Factory.StartNew(() => ProcessQueueAsync(messageBuilder)); }
public void given() { l = "${message}"; evt = new LogEventInfo( LogLevel.Debug, "MessageFormatterTests", CultureInfo.InvariantCulture, "Hello World", null, GenerateException()); evt.Properties.Add("tags", new[] { "skurk:rånarligan" }); }
//TODO onInit maken /// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary> public FilePathLayout(Layout layout, bool cleanupInvalidChars, FilePathKind filePathKind) { _layout = layout; _filePathKind = filePathKind; _cleanupInvalidChars = cleanupInvalidChars; if (_layout == null) { _filePathKind = FilePathKind.Unknown; return; } //do we have to the the layout? if (cleanupInvalidChars || _filePathKind == FilePathKind.Unknown) { //check if fixed var pathLayout2 = layout as SimpleLayout; if (pathLayout2 != null) { var isFixedText = pathLayout2.IsFixedText; if (isFixedText) { cleanedFixedResult = pathLayout2.FixedText; if (cleanupInvalidChars) { //clean first cleanedFixedResult = CleanupInvalidFilePath(cleanedFixedResult); } } //detect absolute if (_filePathKind == FilePathKind.Unknown) { _filePathKind = DetectFilePathKind(pathLayout2); } } else { _filePathKind = FilePathKind.Unknown; } } #if !SILVERLIGHT if (_filePathKind == FilePathKind.Relative) { _baseDir = AppDomainWrapper.CurrentDomain.BaseDirectory; } #endif }
public Rfc5424(Facility facility, Rfc5424Config rfc5424Config, EnforcementConfig enforcementConfig) : base(facility, enforcementConfig) { version = DefaultVersion; hostnameLayout = rfc5424Config.Hostname; appNameLayout = rfc5424Config.AppName; procIdLayout = NilValue; msgIdLayout = NilValue; structuredData = new StructuredData(rfc5424Config.StructuredData, enforcementConfig); disableBom = rfc5424Config.DisableBom; hostnamePolicySet = new FqdnHostnamePolicySet(enforcementConfig, rfc5424Config.DefaultHostname); appNamePolicySet = new AppNamePolicySet(enforcementConfig, rfc5424Config.DefaultAppName); procIdPolicySet = new ProcIdPolicySet(enforcementConfig); msgIdPolicySet = new MsgIdPolicySet(enforcementConfig); utf8MessagePolicy = new Utf8MessagePolicy(enforcementConfig); }
public static string GetMessageInner(bool useJSON, Layout layout, LogEventInfo info, IList<Field> fields) { if (!useJSON) return layout.Render(info); var logLine = new LogLine { TimeStampISO8601 = info.TimeStamp.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), Message = info.FormattedMessage, Level = info.Level.Name, Type = "amqp", Source = new Uri(string.Format("nlog://{0}/{1}", HostName, info.LoggerName)) }; logLine.AddField("exception", info.Exception); if (info.Properties.Count > 0 && info.Properties.ContainsKey("fields")) foreach (var kv in (IEnumerable<KeyValuePair<string, object>>) info.Properties["fields"]) logLine.AddField(kv.Key, kv.Value); if (info.Properties.Count > 0 && info.Properties.ContainsKey("tags")) foreach (var tag in (IEnumerable<string>) info.Properties["tags"]) logLine.AddTag(tag); foreach (var propertyPair in info.Properties) { var key = propertyPair.Key as string; if (key == null || key == "tags" || key == "fields") continue; logLine.AddField((string) propertyPair.Key, propertyPair.Value); } if (fields != null) foreach (Field field in fields) if (logLine.Fields == null || !logLine.Fields.Any(x => x.Key == field.Name)) logLine.AddField(field.Name, field.Layout.Render(info)); logLine.EnsureADT(); return JsonConvert.SerializeObject(logLine); }
/// <summary> /// Initializes a new instance of the <see cref="MethodCallParameter" /> class. /// </summary> /// <param name="layout">The layout to use for parameter value.</param> public MethodCallParameter(Layout layout) { this.Type = typeof(string); this.Layout = layout; }
public StructuredData(StructuredDataConfig sdConfig, EnforcementConfig enforcementConfig) { fromEventProperties = sdConfig.FromEventProperties; sdElements = sdConfig.SdElements.Select(sdElementConfig => new SdElement(sdElementConfig, enforcementConfig)).ToList(); }
/// <summary>Initializes a new instance of the Syslog class</summary> public Syslog() { SyslogServer = "127.0.0.1"; Port = 514; Sender = Assembly.GetCallingAssembly().GetName().Name; Facility = SyslogFacility.Local1; Protocol = ProtocolType.Udp; TimestampFormat = "MMM dd HH:mm:ss"; MachineName = Dns.GetHostName(); SplitNewlines = true; Rfc = RfcNumber.Rfc3164; //Defaults for rfc 5424 ProtocolVersion = 1; ProcId = NilValue; MsgId = NilValue; StructuredData = NilValue; }
/// <summary> /// Initializes a new instance of the <see cref="DatabaseParameterInfo" /> class. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterLayout">The parameter layout.</param> public GelfParameterInfo(string parameterName, Layout parameterLayout) { this.Name = parameterName; this.Layout = parameterLayout; }
/// <summary> /// Initializes a new instance of the <see cref="JsonAttribute" /> class. /// </summary> /// <param name="name">The name of the attribute.</param> /// <param name="layout">The layout of the attribute's value.</param> public JsonAttribute(string name, Layout layout) : this(name, layout, true) { }
/// <summary> /// Renders the layout for the specified logging event by invoking layout renderers. /// </summary> /// <param name="logEvent">The logging event.</param> /// <param name="target"><see cref="System.Text.StringBuilder"/> for the result.</param> protected override void RenderFormattedMessage(LogEventInfo logEvent, System.Text.StringBuilder target) { Layout.RenderAppendBuilder(logEvent, target); }
/// <summary> /// set in Session and test /// </summary> /// <param name="key">set with this key</param> /// <param name="value">set this value</param> /// <param name="expected">expected</param> /// <param name="appSettingLayoutRenderer"></param> /// <remarks>IRenderable is internal</remarks> private void ExecTest(string key, object value, object expected, Layout appSettingLayoutRenderer) { Session[key] = value; var rendered = appSettingLayoutRenderer.Render(LogEventInfo.CreateNullEvent()); Assert.Equal(expected, rendered); }
/// <summary> /// Append rendered layout to the stringbuilder /// </summary> /// <param name="sb">append to this</param> /// <param name="logEvent">event for rendering <paramref name="layout"/></param> /// <param name="layout">append if not <c>null</c></param> private static void AppendLayout(StringBuilder sb, LogEventInfo logEvent, Layout layout) { sb.Append("|"); if (layout != null) sb.Append(layout.Render(logEvent)); }
private static IEnumerable<EventRecord> Write(LogLevel logLevel, EventLogEntryType expectedEventLogEntryType, string logMessage, Layout entryType = null, EventLogTargetOverflowAction overflowAction = EventLogTargetOverflowAction.Truncate, int maxMessageLength = 16384) { var target = CreateEventLogTarget(entryType, "NLog.UnitTests" + Guid.NewGuid().ToString("N"), overflowAction, maxMessageLength); SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); var logger = LogManager.GetLogger("WriteEventLogEntry"); logger.Log(logLevel, logMessage); var eventLog = new EventLog(target.Log); var entries = GetEventRecords(eventLog.Log).ToList(); var expectedSource = target.GetFixedSource(); var filteredEntries = entries.Where(entry => entry.ProviderName == expectedSource && HasEntryType(entry, expectedEventLogEntryType) ); if (overflowAction == EventLogTargetOverflowAction.Discard && logMessage.Length > maxMessageLength) { Assert.False(filteredEntries.Any(), string.Format("No message is expected. But {0} message(s) found entry of type '{1}' from source '{2}'.", filteredEntries.Count(), expectedEventLogEntryType, expectedSource)); } else { Assert.True(filteredEntries.Any(), string.Format("Failed to find entry of type '{0}' from source '{1}'", expectedEventLogEntryType, expectedSource)); } return filteredEntries; }
/// <summary> /// Initializes a new instance of the <see cref="CsvColumn" /> class. /// </summary> /// <param name="name">The name of the column.</param> /// <param name="layout">The layout of the column.</param> public CsvColumn(string name, Layout layout) { this.Name = name; this.Layout = layout; }
public RollbarTarget() { Title = "${message}"; }
/// <summary> /// Renders the layout for the specified logging event by invoking layout renderers. /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The rendered layout.</returns> protected override string GetFormattedMessage(LogEventInfo logEvent) { return(Layout.Render(logEvent)); }
/// <summary> /// Initializes a new instance of the <see cref="MethodCallParameter" /> class. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="layout">The layout.</param> public MethodCallParameter(string parameterName, Layout layout) { this.Type = typeof(string); this.Name = parameterName; this.Layout = layout; }
/// <summary> /// Initializes a new instance of the <see cref="MethodCallParameter" /> class. /// </summary> /// <param name="name">The name of the parameter.</param> /// <param name="layout">The layout.</param> /// <param name="type">The type of the parameter.</param> public MethodCallParameter(string name, Layout layout, Type type) { this.Type = type; this.Name = name; this.Layout = layout; }
/// <summary> /// Initializes a new instance of the <see cref="CsvColumn" /> class. /// </summary> /// <param name="name">The name of the column.</param> /// <param name="layout">The layout of the column.</param> public CsvColumn(string name, Layout layout) { Name = name; Layout = layout; }
/// <summary> /// Initializes a new instance of the <see cref="DatabaseParameterInfo" /> class. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterLayout">The parameter layout.</param> public DatabaseParameterInfo(string parameterName, Layout parameterLayout) { this.Name = parameterName; this.Layout = parameterLayout; }
/// <inheritdoc /> public XmlLayout(string elementName, Layout elementValue) : base(elementName, elementValue) { }
private void AssertMessageCountAndLogLevelForSplittedMessages(LogLevel loglevel, EventLogEntryType expectedEventLogEntryType, Layout entryTypeLayout) { const int maxMessageLength = 16384; const int expectedEntryCount = 2; string messagePart1 = string.Join("", Enumerable.Repeat("l", maxMessageLength)); string messagePart2 = "this part must be splitted"; string testMessage = messagePart1 + messagePart2; var entries = Write(loglevel, expectedEventLogEntryType, testMessage, entryTypeLayout, EventLogTargetOverflowAction.Split, maxMessageLength).ToList(); Assert.Equal(expectedEntryCount, entries.Count); }
public ElastisearchParameterInfo(string name, Layout layout) { this.Name = name; this.Layout = layout; }
private static EventLogTarget CreateEventLogTarget(Layout entryType, string sourceName, EventLogTargetOverflowAction overflowAction, int maxMessageLength) { var target = new EventLogTarget(); //The Log to write to is intentionally lower case!! target.Log = "application"; // set the source explicitly to prevent random AppDomain name being used as the source name target.Source = sourceName; //Be able to check message length and content, the Layout is intentionally only ${message}. target.Layout = new SimpleLayout("${message}"); if (entryType != null) { //set only when not default target.EntryType = entryType; } target.OnOverflow = overflowAction; target.MaxMessageLength = maxMessageLength; return target; }
/// <summary> /// Initializes a new instance of the <see cref="JsonAttribute" /> class. /// </summary> /// <param name="name">The name of the attribute.</param> /// <param name="layout">The layout of the attribute's value.</param> public JsonAttribute(string name, Layout layout) { this.Name = name; this.Layout = layout; }
/// <summary> /// Render <paramref name="layout"/> and add the addresses to <paramref name="mailAddressCollection"/> /// </summary> /// <param name="mailAddressCollection">Addresses appended to this list</param> /// <param name="layout">layout with addresses, ; separated</param> /// <param name="logEvent">event for rendering the <paramref name="layout"/></param> /// <returns>added a address?</returns> private static bool AddAddresses(MailAddressCollection mailAddressCollection, Layout layout, LogEventInfo logEvent) { var added = false; if (layout != null) { foreach (string mail in layout.Render(logEvent).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { mailAddressCollection.Add(mail); added = true; } } return added; }
/// <summary> /// Is this (templated/invalid) path an absolute, relative or unknown? /// </summary> internal static FilePathKind DetectFilePathKind(Layout pathLayout) { var simpleLayout = pathLayout as SimpleLayout; if (simpleLayout == null) { return FilePathKind.Unknown; } return DetectFilePathKind(simpleLayout); }
public JsonField(string name, Layout layout) { Name = name; Layout = layout; }
/// <summary> /// Render layout <paramref name="layout"/> with dummy <see cref="LogEventInfo" />and compare result with <paramref name="expected"/>. /// </summary> protected static void AssertLayoutRendererOutput(Layout layout, string expected) { var logEventInfo = LogEventInfo.Create(LogLevel.Info, "loggername", "message"); AssertLayoutRendererOutput(layout, logEventInfo, expected); }