public static void Clear() { MappedDiagnosticsContext.Remove(TagologContextParamName); }
public static void Save(string context) { MappedDiagnosticsContext.Set(TagologContextParamName, context); }
/// <summary> /// Renders the specified MDC item and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder"> /// The <see cref="StringBuilder" /> to append the rendered data to. /// </param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var msg = MappedDiagnosticsContext.Get(Item); builder.Append(msg); }
/// <summary> /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var settings = new XmlWriterSettings { Indent = this.IndentXml, ConformanceLevel = ConformanceLevel.Fragment, IndentChars = " ", }; var sb = new StringBuilder(); using (XmlWriter xtw = XmlWriter.Create(sb, settings)) { xtw.WriteStartElement("log4j", "event", dummyNamespace); xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace); xtw.WriteAttributeSafeString("logger", logEvent.LoggerName); xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpper(CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture)); xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage); if (logEvent.Exception != null) { xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString()); } if (this.IncludeNdc) { xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, string.Join(this.NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages())); } if (logEvent.Exception != null) { xtw.WriteStartElement("log4j", "throwable", dummyNamespace); xtw.WriteSafeCData(logEvent.Exception.ToString()); xtw.WriteEndElement(); } if (this.IncludeCallSite || this.IncludeSourceInfo) { System.Diagnostics.StackFrame frame = logEvent.UserStackFrame; if (frame != null) { MethodBase methodBase = frame.GetMethod(); Type type = methodBase.DeclaringType; xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace); if (type != null) { xtw.WriteAttributeSafeString("class", type.FullName); } xtw.WriteAttributeSafeString("method", methodBase.ToString()); #if !SILVERLIGHT if (this.IncludeSourceInfo) { xtw.WriteAttributeSafeString("file", frame.GetFileName()); xtw.WriteAttributeSafeString("line", frame.GetFileLineNumber().ToString(CultureInfo.InvariantCulture)); } #endif xtw.WriteEndElement(); if (this.IncludeNLogData) { xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture)); xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace); if (type != null) { xtw.WriteAttributeSafeString("assembly", type.Assembly.FullName); } xtw.WriteEndElement(); xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace); foreach (var contextProperty in logEvent.Properties) { xtw.WriteStartElement("nlog", "data", dummyNLogNamespace); xtw.WriteAttributeSafeString("name", Convert.ToString(contextProperty.Key, CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("value", Convert.ToString(contextProperty.Value, CultureInfo.InvariantCulture)); xtw.WriteEndElement(); } xtw.WriteEndElement(); } } } xtw.WriteStartElement("log4j", "properties", dummyNamespace); if (this.IncludeMdc) { foreach (string key in MappedDiagnosticsContext.GetNames()) { xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", key); xtw.WriteAttributeSafeString("value", String.Format(logEvent.FormatProvider, "{0}", MappedDiagnosticsContext.GetObject(key))); xtw.WriteEndElement(); } } foreach (NLogViewerParameterInfo parameter in this.Parameters) { xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", parameter.Name); xtw.WriteAttributeSafeString("value", parameter.Layout.Render(logEvent)); xtw.WriteEndElement(); } xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4japp"); xtw.WriteAttributeSafeString("value", this.AppInfo); xtw.WriteEndElement(); xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4jmachinename"); #if SILVERLIGHT xtw.WriteAttributeSafeString("value", "silverlight"); #else xtw.WriteAttributeSafeString("value", Environment.MachineName); #endif xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.Flush(); // get rid of 'nlog' and 'log4j' namespace declarations sb.Replace(" xmlns:log4j=\"" + dummyNamespace + "\"", string.Empty); sb.Replace(" xmlns:nlog=\"" + dummyNLogNamespace + "\"", string.Empty); builder.Append(sb.ToString()); } }
private void SetAndFetch(string where, int batchsize, string fldList) { MappedDiagnosticsContext.Set("where", where); this.SetFetchWhereParameters(this.bpehvTableControlKey, where, batchsize, fldList); this.SetTableParametersOnContext(this.bpehvTableControlKey, true); }
public void LoggerIncludesPropertiesInLog() { var formatter = LogSettingsHelper.GetFormatter(); var sink = new NLogHelper.TestSink(); var target = NLogHelper.CreateTarget(sink, DirectSubmissionLogLevel.Debug); var targetProxy = NLogCommon <LoggingConfiguration> .CreateNLogTargetProxy(target); var config = new LoggingConfiguration(); NLogHelper.AddTargetToConfig(config, targetProxy); var logFactory = new LogFactory(config); var logger = logFactory.GetLogger(nameof(LoggerIncludesPropertiesInLog)); // We don't currently record NDC/NDLC #if NLOG_45 var messageTemplate = "This is a message with {Value}"; #else var messageTemplate = "This is a message with {0}"; #endif var mdcKey = "some mdcKey"; var mdcValue = "some mdcValue"; #if !NLOG_2 var mdclKey = "some mdclKey"; var mdclValue = "some mdclValue"; #endif // var nestedScope = "some nested name"; // var nestedDictionary = new Dictionary<string, object> { { "nlcKey", 657 } }; // var dictValues = nestedDictionary.First(); try { MappedDiagnosticsContext.Set(mdcKey, mdcValue); #if !NLOG_2 MappedDiagnosticsLogicalContext.Set(mdclKey, mdclValue); #endif logger.Error(messageTemplate, 123); } finally { MappedDiagnosticsContext.Remove(mdcKey); #if !NLOG_2 MappedDiagnosticsLogicalContext.Remove(mdclKey); #endif } var logEvent = sink.Events.Should().ContainSingle().Subject; // get the rendered log var sb = new StringBuilder(); logEvent.Format(sb, formatter); var log = sb.ToString(); log.Should() .Contain("This is a message with 123") .And.Contain(mdcKey) .And.Contain(mdcValue) #if !NLOG_2 .And.Contain(mdclKey) .And.Contain(mdclValue) #endif // .And.Contain(nestedScope) // .And.Contain(dictValues.Key) // .And.Contain(dictValues.Value.ToString()) .And.Contain(DirectSubmissionLogLevelExtensions.Error); }
public static void Main(string[] args) { //Configuring NLogfrom code: //var config = new NLog.Config.LoggingConfiguration(); //var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" }; //var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); //config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); //config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); //NLog.LogManager.Configuration = config; Random rnd = new Random(); string curRunId = $"ThreadId {Thread.CurrentThread.ManagedThreadId} AppDomainId {AppDomain.CurrentDomain.Id}"; string curTime = DateTime.Now.ToString("h:mm:ss tt"); Console.WriteLine($"Run {curRunId} - Start. {curTime}"); //int sleepTime = rnd.Next(1000, 2000); //Console.WriteLine($"Sleeping for {sleepTime} ms"); //System.Threading.Thread.Sleep(sleepTime); //Configuring NLog from xml string: sampleNLogXMLConfig = replacePlaceHolderInConfigString(); StringReader sr = new StringReader(sampleNLogXMLConfig); XmlReader xr = XmlReader.Create(sr); XmlLoggingConfiguration config = new XmlLoggingConfiguration(xr, null, false); //This line throws in case of invalid configuration LogManager.Configuration = config; logger = NLog.LogManager.GetCurrentClassLogger(); LogManager.ReconfigExistingLoggers(); registerToEventViewer(EVENT_VIEWER_SRC_NAME); //NLog is now configured just as if the XML above had been in NLog.config or app.config uint numOfLogWrites = 5; List <Task> tasks = new List <Task>(); GlobalDiagnosticsContext.Set("globalItemVal", "This is a global param val"); for (int i = 0; i < numOfLogWrites; i++) { Task curTask = new Task((object state) => { int index = (int)state; //int msgSizeInBytes = rnd.Next(1, 60); int alphabetRange = (int)'z' - (int)'a'; char c = 'a'; c += (char)(index % alphabetRange); //string content = new string(c, 15 * 1024); string content = $"{c}{c}{c}"; double currentTimeInSeconds = getCurrentTimeInSeconds(); string entryBody = $"logMsg#{index} time:{currentTimeInSeconds}{Environment.NewLine}{content}"; //logEntry.AddProps(new Dictionary<string, object> { { $"prop{index}", $"val{index}" } }); if (index % 2 == 0) { if (index == 2) { MappedDiagnosticsContext.Set("mdcItemVal", null); } else { MappedDiagnosticsContext.Set("mdcItemVal", $"This is a MappedDiagnosticsContext param val, index {index}"); } } else if (index % 3 == 0) { MappedDiagnosticsLogicalContext.Set("mdlcItemVal", $"This is a MappedDiagnosticsLogicalContext param val, index {index}"); } writeToLog(entryBody); //exception write tst: //else //{ // Exception dummyEx = new Exception($"dummyEx#{index}"); // writeToLog(dummyEx, entryBody); //} }, (object)i); curTask.Start(TaskScheduler.Default); tasks.Add(curTask); //if (i % 2 == 0) //{ // int sleepTime = rnd.Next(0, 1500); // Console.WriteLine($"Sleeping for {sleepTime} ms"); // System.Threading.Thread.Sleep(sleepTime); //} } Task.WaitAll(tasks.ToArray()); curTime = DateTime.Now.ToString("h:mm:ss tt"); Console.WriteLine($"Run ${curRunId} - End. {curTime}"); }
public void SetCustomerId(string CustomerId) { //https://github.com/nlog/NLog/wiki/Mdc-Layout-Renderer MappedDiagnosticsContext.Set("CustomerId", CustomerId); }
/// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void SetContextValue(string key, string value) { MappedDiagnosticsContext.Set(key, value); }
public void Start_WebSocket() { MappedDiagnosticsContext.Set(StringUtility.LOGKEYINFO, StringUtility.WEBSOCKETLOG); txtLogger.Info("Start to connect to the web server at [{0}]", m_serverUrl); try { bool loc_ip_re = GetLocalIP(ref m_localIp); if (!loc_ip_re) { txtLogger.Error("Get local IP ERROR"); return; } m_webSsocket = new WebSocket(m_serverUrl); if (null == m_webSsocket) { txtLogger.Error("New web socket fail "); return; } m_webSsocket.WaitTime = TimeSpan.FromSeconds(m_reconnect); } catch (Exception ex) { txtLogger.Error("New web socket exception: {0}", ex.Message); return; } try { m_webSsocket.EmitOnPing = true; // 是否接收ping标志 m_webSsocket.OnMessage += (sender, e) => { if (!e.IsPing) { MappedDiagnosticsContext.Set(StringUtility.LOGKEYINFO, StringUtility.WEBSOCKETLOG); // if is not ping message, handle the message try { if (e.IsText) { string writeBack = string.Empty; txtLogger.Info(">>>>>>>>>> Receive message from rfid server: {0}", e.Data); JObject jobj = (JObject)JsonConvert.DeserializeObject(e.Data); if (jobj == null) { txtLogger.Error("Convert the string to json fail: {0}", e.Data); m_webSsocket.Send("{\"result\":\"convert to json error\"}"); } else { //每一次收到数据都新申请对象,确保没有以前遗留数据 ReaderParameter readerPara = new ReaderParameter(); CommFunc commFunc = new CommFunc(); //解析json数据到ReaderParameter对象 commFunc.ParseJsonObj(jobj, ref readerPara); // TODO: 读写器操作 writeBack = "盘点结果......."; m_webSsocket.Send(writeBack); } } else { txtLogger.Error("Receive other type message: {0}", e.ToString()); } } catch (Exception ex) { txtLogger.Error("Receive message handle execption: {0}", ex.Message); } } // else {going to add} }; m_webSsocket.OnOpen += (sender, e) => { MappedDiagnosticsContext.Set(StringUtility.LOGKEYINFO, StringUtility.WEBSOCKETLOG); txtLogger.Info("Connect to the server success"); //if need to add register info? m_webSsocket.Send(m_localIp); txtLogger.Info("Send register info, {0}", m_localIp); }; m_webSsocket.OnClose += (sender, e) => { MappedDiagnosticsContext.Set(StringUtility.LOGKEYINFO, StringUtility.WEBSOCKETLOG); txtLogger.Info("The websocket connect is closed, {0}", e.Reason); }; m_webSsocket.OnError += (sender, e) => { MappedDiagnosticsContext.Set(StringUtility.LOGKEYINFO, StringUtility.WEBSOCKETLOG); txtLogger.Error("The websocket have an error={0}", e.Message); }; m_webSsocket.Connect(); } catch (Exception ex) { txtLogger.Error("WebSocket handle exception = {0}", ex.Message); m_webSsocket.Close(); } // 断线重连 while (true) { if (!m_webSsocket.Ping()) { //if ping is not on, reconnect try { m_webSsocket.Close(); MappedDiagnosticsContext.Set(StringUtility.LOGKEYINFO, StringUtility.WEBRECONNECT); txtLogger.Info("Start to reconnect to the web server at [{0}],[{1}]", m_serverUrl, m_webSsocket.ReadyState); m_webSsocket.Connect(); } catch (Exception ex) { MappedDiagnosticsContext.Set(StringUtility.LOGKEYINFO, StringUtility.WEBRECONNECT); txtLogger.Error("Reconnect to the web server exception: [{0}]", ex.Message); m_webSsocket.Close(); } } // if ping is doing // m_webSsocket.Send(m_localIp); Thread.Sleep(m_reconnect * 1000); } }
public void SetThreadProperty(string key, object value) { MappedDiagnosticsContext.Set(key, value); }
/// <summary> /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { StringBuilder sb = new StringBuilder(); using (XmlWriter xtw = XmlWriter.Create(sb, _xmlWriterSettings)) { xtw.WriteStartElement("log4j", "event", dummyNamespace); xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace); xtw.WriteAttributeSafeString("logger", LoggerName != null ? LoggerName.Render(logEvent) : logEvent.LoggerName); xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpperInvariant()); xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture)); xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage); if (logEvent.Exception != null) { // TODO Why twice the exception details? xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString()); } string ndcContent = null; if (IncludeNdc) { ndcContent = string.Join(NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages()); } #if !SILVERLIGHT if (IncludeNdlc) { if (ndcContent != null) { //extra separator ndcContent += NdcItemSeparator; } ndcContent += string.Join(NdlcItemSeparator, NestedDiagnosticsLogicalContext.GetAllMessages()); } #endif if (ndcContent != null) { //NDLC and NDC should be in the same element xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, ndcContent); } if (logEvent.Exception != null) { // TODO Why twice the exception details? xtw.WriteStartElement("log4j", "throwable", dummyNamespace); xtw.WriteSafeCData(logEvent.Exception.ToString()); xtw.WriteEndElement(); } if (IncludeCallSite || IncludeSourceInfo) { if (logEvent.CallSiteInformation != null) { MethodBase methodBase = logEvent.CallSiteInformation.GetCallerStackFrameMethod(0); string callerClassName = logEvent.CallSiteInformation.GetCallerClassName(methodBase, true, true, true); string callerMemberName = logEvent.CallSiteInformation.GetCallerMemberName(methodBase, true, true, true); xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace); if (!string.IsNullOrEmpty(callerClassName)) { xtw.WriteAttributeSafeString("class", callerClassName); } xtw.WriteAttributeSafeString("method", callerMemberName); #if !SILVERLIGHT if (IncludeSourceInfo) { xtw.WriteAttributeSafeString("file", logEvent.CallSiteInformation.GetCallerFilePath(0)); xtw.WriteAttributeSafeString("line", logEvent.CallSiteInformation.GetCallerLineNumber(0).ToString(CultureInfo.InvariantCulture)); } #endif xtw.WriteEndElement(); if (IncludeNLogData) { xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture)); xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace); var type = methodBase?.DeclaringType; if (type != null) { xtw.WriteAttributeSafeString("assembly", type.GetAssembly().FullName); } xtw.WriteEndElement(); xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace); AppendProperties("nlog", xtw, logEvent); xtw.WriteEndElement(); } } } xtw.WriteStartElement("log4j", "properties", dummyNamespace); if (IncludeMdc) { foreach (string key in MappedDiagnosticsContext.GetNames()) { string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsContext.GetObject(key)); if (propertyValue == null) { continue; } xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", key); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } #if !SILVERLIGHT if (IncludeMdlc) { foreach (string key in MappedDiagnosticsLogicalContext.GetNames()) { string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsLogicalContext.GetObject(key)); if (propertyValue == null) { continue; } xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", key); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } #endif if (IncludeAllProperties) { AppendProperties("log4j", xtw, logEvent); } if (Parameters.Count > 0) { foreach (NLogViewerParameterInfo parameter in Parameters) { xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", parameter.Name); xtw.WriteAttributeSafeString("value", parameter.Layout.Render(logEvent)); xtw.WriteEndElement(); } } xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4japp"); xtw.WriteAttributeSafeString("value", AppInfo); xtw.WriteEndElement(); xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4jmachinename"); xtw.WriteAttributeSafeString("value", _machineName); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.Flush(); // get rid of 'nlog' and 'log4j' namespace declarations sb.Replace(dummyNamespaceRemover, string.Empty); sb.Replace(dummyNLogNamespaceRemover, string.Empty); sb.CopyTo(builder); // StringBuilder.Replace is not good when reusing the StringBuilder } }
/// <summary> /// Gets or sets the value of a property /// </summary> /// <value> /// The value for the property with the specified key /// </value> /// <remarks> /// <para> /// Gets or sets the value of a property /// </para> /// </remarks> public object this[string key] { get { return(MappedDiagnosticsContext.Get(key)); } set { MappedDiagnosticsContext.Set(key, value); } }
public void Log4JXmlTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout='${log4jxmlevent:includeCallSite=true:includeSourceInfo=true:includeMdc=true:includeMdlc=true:includeMdlc=true:IncludeAllProperties=true:ndcItemSeparator=\:\::includenlogdata=true}' /> </targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); MappedDiagnosticsContext.Clear(); NestedDiagnosticsContext.Clear(); MappedDiagnosticsContext.Set("foo1", "bar1"); MappedDiagnosticsContext.Set("foo2", "bar2"); MappedDiagnosticsLogicalContext.Clear(); MappedDiagnosticsLogicalContext.Set("foo3", "bar3"); NestedDiagnosticsContext.Push("baz1"); NestedDiagnosticsContext.Push("baz2"); NestedDiagnosticsContext.Push("baz3"); ILogger logger = LogManager.GetLogger("A"); var logEventInfo = LogEventInfo.Create(LogLevel.Debug, "A", new Exception("Hello Exception", new Exception("Goodbye Exception")), null, "some message"); logEventInfo.Properties["nlogPropertyKey"] = "nlogPropertyValue"; logger.Log(logEventInfo); string result = GetDebugLastMessage("debug"); string wrappedResult = "<log4j:dummyRoot xmlns:log4j='http://log4j' xmlns:nlog='http://nlog'>" + result + "</log4j:dummyRoot>"; Assert.NotEqual("", result); // make sure the XML can be read back and verify some fields StringReader stringReader = new StringReader(wrappedResult); using (XmlReader reader = XmlReader.Create(stringReader)) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "log4j") { switch (reader.LocalName) { case "dummyRoot": break; case "event": Assert.Equal("DEBUG", reader.GetAttribute("level")); Assert.Equal("A", reader.GetAttribute("logger")); var epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); long timestamp = Convert.ToInt64(reader.GetAttribute("timestamp")); var time = epochStart.AddMilliseconds(timestamp); var now = DateTime.UtcNow; Assert.True(now.Ticks - time.Ticks < TimeSpan.FromSeconds(3).Ticks); Assert.Equal(Thread.CurrentThread.ManagedThreadId.ToString(), reader.GetAttribute("thread")); break; case "message": reader.Read(); Assert.Equal("some message", reader.Value); break; case "NDC": reader.Read(); Assert.Equal("baz3::baz2::baz1", reader.Value); break; case "locationInfo": Assert.Equal(MethodBase.GetCurrentMethod().DeclaringType.FullName, reader.GetAttribute("class")); Assert.Equal(MethodBase.GetCurrentMethod().ToString(), reader.GetAttribute("method")); break; case "properties": break; case "throwable": reader.Read(); Assert.Contains("Hello Exception", reader.Value); Assert.Contains("Goodbye Exception", reader.Value); break; case "data": string name = reader.GetAttribute("name"); string value = reader.GetAttribute("value"); switch (name) { case "log4japp": Assert.Equal(AppDomain.CurrentDomain.FriendlyName + "(" + Process.GetCurrentProcess().Id + ")", value); break; case "log4jmachinename": Assert.Equal(Environment.MachineName, value); break; case "foo1": Assert.Equal("bar1", value); break; case "foo2": Assert.Equal("bar2", value); break; case "foo3": Assert.Equal("bar3", value); break; case "nlogPropertyKey": Assert.Equal("nlogPropertyValue", value); break; default: Assert.True(false, "Unknown <log4j:data>: " + name); break; } break; default: throw new NotSupportedException("Unknown element: " + reader.LocalName); } continue; } if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "nlog") { switch (reader.LocalName) { case "eventSequenceNumber": break; case "locationInfo": Assert.Equal(this.GetType().Assembly.FullName, reader.GetAttribute("assembly")); break; case "properties": break; case "data": var name = reader.GetAttribute("name"); var value = reader.GetAttribute("value"); Assert.Equal("nlogPropertyKey", name); Assert.Equal("nlogPropertyValue", value); break; default: throw new NotSupportedException("Unknown element: " + reader.LocalName); } } } } }
private void RenderJsonFormattedMessage(LogEventInfo logEvent, StringBuilder sb) { //Memory profiling pointed out that using a foreach-loop was allocating //an Enumerator. Switching to a for-loop avoids the memory allocation. for (int i = 0; i < this.Attributes.Count; i++) { var attrib = this.Attributes[i]; string text = attrib.LayoutWrapper.Render(logEvent); if (!string.IsNullOrEmpty(text)) { AppendJsonAttributeValue(attrib.Name, attrib.Encode, text, sb); } } if (this.IncludeMdc) { foreach (string key in MappedDiagnosticsContext.GetNames()) { if (string.IsNullOrEmpty(key)) { continue; } object propertyValue = MappedDiagnosticsContext.GetObject(key); AppendJsonPropertyValue(key, propertyValue, sb); } } #if NET4_0 || NET4_5 if (this.IncludeMdlc) { foreach (string key in MappedDiagnosticsLogicalContext.GetNames()) { if (string.IsNullOrEmpty(key)) { continue; } object propertyValue = MappedDiagnosticsLogicalContext.GetObject(key); AppendJsonPropertyValue(key, propertyValue, sb); } } #endif if (this.IncludeAllProperties && logEvent.HasProperties) { foreach (var prop in logEvent.Properties) { //Determine property name string propName = Internal.XmlHelper.XmlConvertToString(prop.Key ?? string.Empty); if (string.IsNullOrEmpty(propName)) { continue; } //Skips properties in the ExcludeProperties list if (this.ExcludeProperties.Contains(propName)) { continue; } AppendJsonPropertyValue(propName, prop.Value, sb); } } CompleteJsonMessage(sb); }
public void MDCTest1() { List <Exception> exceptions = new List <Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { MappedDiagnosticsContext.Clear(); Assert.False(MappedDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo")); Assert.False(MappedDiagnosticsContext.Contains("foo2")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo2")); Assert.Equal(0, MappedDiagnosticsContext.GetNames().Count); MappedDiagnosticsContext.Set("foo", "bar"); MappedDiagnosticsContext.Set("foo2", "bar2"); Assert.True(MappedDiagnosticsContext.Contains("foo")); Assert.Equal("bar", MappedDiagnosticsContext.Get("foo")); Assert.Equal(2, MappedDiagnosticsContext.GetNames().Count); MappedDiagnosticsContext.Remove("foo"); Assert.False(MappedDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo")); Assert.True(MappedDiagnosticsContext.Contains("foo2")); Assert.Equal("bar2", MappedDiagnosticsContext.Get("foo2")); Assert.Equal(1, MappedDiagnosticsContext.GetNames().Count); Assert.True(MappedDiagnosticsContext.GetNames().Contains("foo2")); Assert.Null(MappedDiagnosticsContext.GetObject("foo3")); MappedDiagnosticsContext.Set("foo3", new { One = 1 }); } catch (Exception exception) { lock (exceptions) { exceptions.Add(exception); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); }
protected BaseLemmingJob() { MappedDiagnosticsContext.Set("JobId", Id.ToString("N")); }
private object GetValue() { //don't use MappedDiagnosticsContext.Get to ensure we are not locking the Factory (indirect by LogManager.Configuration). return(MappedDiagnosticsContext.GetObject(Item)); }
private static void SolveFW(INamedMOProblem Problem, string PathToOutDir, int MaxRun) { MappedDiagnosticsContext.Set("thread_id", $"_{Thread.CurrentThread.ManagedThreadId}_"); Logger logger = LogManager.GetLogger("Main"); const int numParams = 6; object[][] parameters = { //new object[numParams] {250, 600, 10, 20, 30, 1.1}, new object[numParams] { 300, 700, 20, 8, 15, 0.025 }, new object[numParams] { 300, 1000, 25, 8, 17, 0.05 }, new object[numParams] { 400, 900, 15, 8, 12, 0.1 }, new object[numParams] { 350, 750, 20, 10, 19, 0.15 } }; string pathToXml = Path.Combine(PathToOutDir, $"{Problem.Name}_res.xml"); logger.Info($"Open a xml file. '{pathToXml}'"); var normalGen = new NormalGen(); var contGen = new ContGen(); MOFWOptimizer opt = new MOFWOptimizer(contGen, normalGen); using (XmlWriter writer = XmlWriter.Create(pathToXml)) { writer.WriteStartDocument(); writer.WriteStartElement("Problem"); Dictionary <string, string> problemDesc = new Dictionary <string, string> { ["Name"] = Problem.Name, ["DimDec"] = Problem.LowerBounds.Count.ToString(), ["DimObj"] = Problem.CountObjs.ToString(), }; foreach (var name in problemDesc) { writer.WriteAttributeString(name.Key, name.Value); } writer.WriteStartElement("Bounds"); foreach (var bound in Problem.LowerBounds.Zip(Problem.UpperBounds, (low, upp) => (Lower: low, Upper: upp))) { writer.WriteStartElement("Bound"); writer.WriteAttributeString("LowerB", bound.Lower.ToString()); writer.WriteAttributeString("UpperB", bound.Upper.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); logger.Info("Start solving with MOFW."); foreach (var par in Enumerable.Range(0, parameters.Length).Zip(parameters, (num, par) => (Num: num, Parameters: par))) { logger.Info($"Try to find solution with {par.Num}th configuration of {parameters.Length}"); writer.WriteStartElement("Experiment"); writer.WriteStartElement("OptParams"); FWParams pars = CreateParams <FWParams>(par.Parameters); var paramsType = pars.GetType(); foreach (var prop in paramsType.GetProperties()) { if (prop.PropertyType == typeof(bool)) { continue; } writer.WriteStartElement("Param"); writer.WriteAttributeString(prop.Name, prop.GetValue(pars).ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("Runs"); for (int i = 0; i < MaxRun; i++) { logger.Info($"Run {i} of {MaxRun}"); writer.WriteStartElement("Run"); try { opt.Minimize(pars, Problem); writer.WriteStartElement("Decisions"); foreach (var agent in opt.ParetoFront) { writer.WriteStartElement("Point"); for (int coordIndex = 0; coordIndex < agent.Point.Count; coordIndex++) { writer.WriteAttributeString($"x{coordIndex + 1}", agent.Point[coordIndex].ToString()); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteStartElement("Targets"); foreach (var agent in opt.ParetoFront) { writer.WriteStartElement("Target"); for (int coordIndex = 0; coordIndex < agent.Objs.Count; coordIndex++) { writer.WriteAttributeString($"F{coordIndex + 1}", agent.Objs[coordIndex].ToString()); } writer.WriteEndElement(); } writer.WriteEndElement(); } catch (Exception exc) { logger.Error(exc, "Error was in optimization process."); logger.Info("Recreate optimization method."); opt = new MOFWOptimizer(); logger.Info($"Skip run {i}."); } writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndElement(); } } logger.Info("Close a xml file."); MappedDiagnosticsContext.Remove("thread_id"); }
/// <summary> /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { StringBuilder sb = new StringBuilder(); using (XmlWriter xtw = XmlWriter.Create(sb, this.xmlWriterSettings)) { xtw.WriteStartElement("log4j", "event", dummyNamespace); xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace); xtw.WriteAttributeSafeString("logger", logEvent.LoggerName); xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpper(CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture)); xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage); if (logEvent.Exception != null) { xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString()); } if (this.IncludeNdc) { xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, string.Join(this.NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages())); } if (logEvent.Exception != null) { xtw.WriteStartElement("log4j", "throwable", dummyNamespace); xtw.WriteSafeCData(logEvent.Exception.ToString()); xtw.WriteEndElement(); } if (this.IncludeCallSite || this.IncludeSourceInfo) { System.Diagnostics.StackFrame frame = logEvent.UserStackFrame; if (frame != null) { MethodBase methodBase = frame.GetMethod(); Type type = methodBase.DeclaringType; xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace); if (type != null) { xtw.WriteAttributeSafeString("class", type.FullName); } xtw.WriteAttributeSafeString("method", methodBase.ToString()); #if !SILVERLIGHT if (this.IncludeSourceInfo) { xtw.WriteAttributeSafeString("file", frame.GetFileName()); xtw.WriteAttributeSafeString("line", frame.GetFileLineNumber().ToString(CultureInfo.InvariantCulture)); } #endif xtw.WriteEndElement(); if (this.IncludeNLogData) { xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture)); xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace); if (type != null) { xtw.WriteAttributeSafeString("assembly", type.Assembly.FullName); } xtw.WriteEndElement(); } } } if (this.IncludeNLogData) { xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace); if (logEvent.HasProperties) { foreach (var contextProperty in logEvent.Properties) { string propertyKey = XmlHelper.XmlConvertToString(contextProperty.Key); if (string.IsNullOrEmpty(propertyKey)) { continue; } string propertyValue = XmlHelper.XmlConvertToString(contextProperty.Value); if (propertyValue == null) { continue; } xtw.WriteStartElement("nlog", "data", dummyNLogNamespace); xtw.WriteAttributeSafeString("name", propertyKey); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } xtw.WriteEndElement(); } xtw.WriteStartElement("log4j", "properties", dummyNamespace); if (this.IncludeMdc) { foreach (string key in MappedDiagnosticsContext.GetNames()) { string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsContext.GetObject(key)); if (propertyValue == null) { continue; } xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", key); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } #if NET4_0 || NET4_5 if (this.IncludeMdlc) { foreach (string key in MappedDiagnosticsLogicalContext.GetNames()) { string propertyValue = XmlHelper.XmlConvertToString(MappedDiagnosticsLogicalContext.GetObject(key)); if (propertyValue == null) { continue; } xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", key); xtw.WriteAttributeSafeString("value", propertyValue); xtw.WriteEndElement(); } } #endif if (this.Parameters.Count > 0) { foreach (NLogViewerParameterInfo parameter in this.Parameters) { xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", parameter.Name); xtw.WriteAttributeSafeString("value", parameter.Layout.Render(logEvent)); xtw.WriteEndElement(); } } xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4japp"); xtw.WriteAttributeSafeString("value", this.AppInfo); xtw.WriteEndElement(); xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4jmachinename"); xtw.WriteAttributeSafeString("value", this.machineName); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.Flush(); // get rid of 'nlog' and 'log4j' namespace declarations sb.Replace(dummyNamespaceRemover, string.Empty); sb.Replace(dummyNLogNamespaceRemover, string.Empty); builder.Append(sb.ToString()); // StringBuilder.Replace is not good when reusing the StringBuilder } }
public void SetMappedContextField(string item, string value) { MappedDiagnosticsContext.Set(item, value); }