protected void SetTableParametersOnContext(Tuple <string, string> tableKey, bool setMdc = false) { var controlParameters = this.GetTableParameters(tableKey); var tableName = tableKey.Item2; if (controlParameters == null) { return; } this.SetContextParameter(tableName, TableControlParameters.ParameterNameFillMode, controlParameters.FillMode); this.SetContextParameter(tableName, "WhereString", controlParameters.WhereClause); this.SetContextParameter(tableName, "BatchSize", controlParameters.PageSize); this.SetContextParameter(tableName, "FindSeq", controlParameters.FindSeq); this.SetContextParameter(tableName, "ActivateDataRelation", controlParameters.ActivateDataRelation); this.SetContextParameter(tableName, "IncludeFields", controlParameters.IncludeFields); this.SetContextParameter(tableName, "ExcludeFields", controlParameters.ExcludeFields); this.SetContextParameter(tableName, "DataRelationReposition", controlParameters.DataRelationReposition ? "yes" : "no"); this.SetContextParameter(tableName, "cono", this.connection.CompanyNumber); this.SetContextParameter(tableName, "operinit", this.connection.Operator); this.SetContextParameter(tableName, "SavedRowID", controlParameters.SavedRowId); this.SetContextParameter(tableName, "RestartRowID", controlParameters.RestartRowId ? "yes" : "no"); if (setMdc) { if (string.IsNullOrEmpty(controlParameters.IncludeFields)) { MappedDiagnosticsContext.Set("fldlist", controlParameters.IncludeFields); MappedDiagnosticsContext.Set("exclude", "No"); } if (string.IsNullOrEmpty(controlParameters.ExcludeFields)) { MappedDiagnosticsContext.Set("fldlist", controlParameters.ExcludeFields); MappedDiagnosticsContext.Set("exclude", "Yes"); } MappedDiagnosticsContext.Set("batchsize", controlParameters.PageSize.ToString()); } }
public void BasicAuthEmailTest() { try { var mmt = new MockMailTarget { From = "*****@*****.**", To = "*****@*****.**", SmtpServer = "server1", SmtpAuthentication = SmtpAuthenticationMode.Basic, SmtpUserName = "******", SmtpPassword = "******", }; mmt.Initialize(null); var exceptions = new List <Exception>(); MappedDiagnosticsContext.Set("username", "u1"); MappedDiagnosticsContext.Set("password", "p1"); mmt.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "MyLogger", "log message 1").WithContinuation(exceptions.Add)); Assert.Null(exceptions[0]); Assert.Equal(1, mmt.CreatedMocks.Count); var mock = mmt.CreatedMocks[0]; var credential = mock.Credentials as NetworkCredential; Assert.NotNull(credential); Assert.Equal("u1", credential.UserName); Assert.Equal("p1", credential.Password); Assert.Equal(string.Empty, credential.Domain); } finally { MappedDiagnosticsContext.Clear(); } }
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); } } } } }
public void SetContext(string item, object value) { MappedDiagnosticsContext.Set(item, value); }
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()); }
/// <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); } }
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"); }
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}"); }
protected BaseLemmingJob() { MappedDiagnosticsContext.Set("JobId", Id.ToString("N")); }
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); } }
/// <summary> /// /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void SetContextValue(string key, string value) { MappedDiagnosticsContext.Set(key, value); }
public void SetThreadProperty(string key, object value) { MappedDiagnosticsContext.Set(key, value); }
public void SetCustomerId(int CustomerId) { // https://github.com/nlog/NLog/wiki/Mdc-Layout-Renderer MappedDiagnosticsContext.Set("CustomerId", CustomerId); }
public static void Save(string context) { MappedDiagnosticsContext.Set(TagologContextParamName, context); }
private void SetAndFetch(string where, int batchsize, string fldList) { MappedDiagnosticsContext.Set("where", where); this.SetFetchWhereParameters(this.convTableControlKey, where, batchsize, fldList); this.SetTableParametersOnContext(this.convTableControlKey, true); }
public void SetMappedContextField(string item, string value) { MappedDiagnosticsContext.Set(item, value); }