public string Format(LogEntry entry) { StringBuilder sb = new StringBuilder(); int stop = Math.Min(entry.StackFrames.Length, Count); for (int i = SkipCount; i < stop; ++i) { StackFrame frame = entry.StackFrames[i]; if (frame == null) { sb.Append("UnknownFrame <--"); continue; } MethodBase method = frame.GetMethod(); if (method == null) { sb.Append("UnknownFrame <--"); continue; } string typeName = method.ReflectedType == null ? "UnknownType" : method.ReflectedType.Name ?? "UnknownTypeName"; string methodName = method.Name ?? "UnknownMethodName"; sb.Append(string.Format("{0}.{1}<--", typeName, methodName)); } string temp = sb.ToString(); if (temp.Length > 3) temp = temp.Remove(temp.Length - 3); return PadLength == 0 ? temp : temp.PadRight(PadLength); }
public override void Write(LogEntry entry) { var fmt = EntryFormatter ?? entry.Logger.LogManager.GetFormatter<string>(); var msg = fmt.Convert(entry); switch (entry.Level) { case Level.Trace: case Level.Debug: Trace.WriteLine(msg); break; case Level.Info: Trace.TraceInformation(msg); break; case Level.Warn: Trace.TraceWarning(msg); break; case Level.Error: Trace.TraceError(msg); break; case Level.Fatal: Trace.Fail(msg); break; default: throw new ArgumentOutOfRangeException(); } }
public string FormatEntry(LogEntry logEntry, bool tracingInfo = false) { string tracingInformation = ""; if (tracingInfo) { if (logEntry.LogException != null) { tracingInformation = String.Format("\nException message: {0}\nStack trace: {1}", logEntry.LogException.Message, logEntry.LogException.StackTrace); } else { if (logEntry.Priority == LogPriority.ERROR) tracingInformation = String.Format("\nStack trace: \n{0}", !string.IsNullOrEmpty(logEntry.currentStackTrace) ? logEntry.currentStackTrace : "unknown"); else if (logEntry.Priority == LogPriority.DEBUG) tracingInformation = String.Format("\nMethod name: {0}\nSource file path:\n{1} Line: {2}", logEntry.MethodName, logEntry.SourceFilePath, logEntry.LineNumber); } } return String.Format("{0} [{1}] [{2}] {3} {4} {5}", logEntry.Time, !string.IsNullOrEmpty(logEntry.ContextName) ? logEntry.ContextName : "", logEntry.Priority.ToString(), logEntry.Message, logEntry.type != null ? String.Format("\nAssembly: {0} Type Info: {0}", Assembly.GetCallingAssembly(), logEntry.type.FullName) : "", tracingInformation ); }
protected void Btn_Update_Click(object sender, EventArgs e) { try { using (StreamWriter sw = new StreamWriter(Server.MapPath(string.Format("../SideBar/{0}",Dl_CustomizePage.SelectedValue)), false, System.Text.Encoding.Unicode)) { sw.Write(Txt_SourceCode.Text); } logwrite.Write( "User Update SideBar Success.", Category.General, Priority.Low ); } catch (Exception ex) { LogEntry entry=new LogEntry (); entry.Severity=System.Diagnostics.TraceEventType.Error; entry.Message=string.Format("Exception:{0}, Inner Exception:{1}", ex.Message, ex.InnerException.Message); entry.Categories.Add(Category.Exception); entry.Priority=Priority.High; logwrite.Write(entry); throw; } }
public override void Log(LogEntry logEntry) { lock (_bufferLock) { _bufferedEntries.Add(logEntry); } lock (_timerLock) { if (_maxTimer == null) { _minTimer = new Timer(MinimumWaitTime.TotalMilliseconds) { AutoReset = false }; _maxTimer = new Timer(MaximumWaitTime.TotalMilliseconds) { AutoReset = false }; _minTimer.Elapsed += UnspoolBuffer; _maxTimer.Elapsed += UnspoolBuffer; _minTimer.Start(); _maxTimer.Start(); } else { if (_minTimer != null) { _minTimer.Close(); } _minTimer = new Timer(MinimumWaitTime.TotalMilliseconds) { AutoReset = false }; _minTimer.Elapsed += UnspoolBuffer; _minTimer.Start(); } } }
private SyndicationItem FormatLogEntry(LogEntry entry, string repo) { var markdownParser = new Markdown(true); var item = new SyndicationItem(); item.Id = entry.CommitHash; item.Title = new TextSyndicationContent(entry.Subject); item.Content = SyndicationContent.CreateHtmlContent(markdownParser.Transform(entry.Subject + "\n\n" + entry.Body)); item.LastUpdatedTime = entry.AuthorDate; item.PublishDate = entry.CommitterDate; item.Links.Add(SyndicationLink.CreateAlternateLink(new Uri(Url.Action("ViewCommit", "Browse", new { repo, @object = entry.CommitHash }), UriKind.Relative))); item.Categories.Add(new SyndicationCategory("commit")); if (entry.Parents.Count > 1) { item.Categories.Add(new SyndicationCategory("merge")); } item.Authors.Add(new SyndicationPerson(entry.AuthorEmail, entry.Author, null)); if (entry.Author != entry.Committer || entry.AuthorEmail != entry.CommitterEmail) { item.Contributors.Add(new SyndicationPerson(entry.CommitterEmail, entry.Committer, null)); } return item; }
private void OnLogged(string message) { var logEntry = new LogEntry(); logEntry.Message = message; LogEntries.Add(logEntry); }
void CreateRandomLogEntries(int howMany) { for (int i = 0; i < howMany; i++) { float date = Random.Range(i* RTSDirector.instance.gameDay, ((i+1))*RTSDirector.instance.gameDay)/ howMany; LogEntry scratchLogEntry = new LogEntry(); scratchLogEntry.date = date; //scratchLogEntry.location = whatever; scratchLogEntry.who = scratchLogEntry.whoArray[Random.Range(0, scratchLogEntry.whoArray.Length)] ; scratchLogEntry.didWhat = scratchLogEntry.didWhatArray[Random.Range(0, scratchLogEntry.didWhatArray.Length)]; scratchLogEntry.whatSubject = scratchLogEntry.whatSubjectArray[Random.Range(0, scratchLogEntry.whatSubjectArray.Length)]; if(scratchLogEntry.whatSubject == "floating debris") scratchLogEntry.doingWhat = ""; else scratchLogEntry.doingWhat = scratchLogEntry.doingWhatArray[Random.Range(0, scratchLogEntry.doingWhatArray.Length)]; scratchLogEntry.where = scratchLogEntry.whereArray[Random.Range(0, scratchLogEntry.whereArray.Length)]; scratchLogEntry.message = "Day " + scratchLogEntry.date.ToString("n1") + ": "+ scratchLogEntry.who+ " "+ scratchLogEntry.didWhat + " "+ scratchLogEntry.whatSubject + " "+ scratchLogEntry.doingWhat + " "+ scratchLogEntry.where + ".\n\n"; logEntryList.Add(scratchLogEntry); } }
/// <summary> /// Append the log entry to the configured text file. /// </summary> /// <param name="logEntry"><see cref="LogEntry"></see> to be appended to logging file</param> protected override void SendMessageCore(LogEntry logEntry) { if (ValidateParameters(logEntry)) { try { webservice.Logging ws = new webservice.Logging(); ws.Url = this.wsSinkData.Url; webservice.WSLogEntry wsLogEntry = new webservice.WSLogEntry(); wsLogEntry.Message = logEntry.Message; wsLogEntry.Priority = logEntry.Priority; wsLogEntry.Category = logEntry.Category; wsLogEntry.EventId = logEntry.EventId; wsLogEntry.Severity = (webservice.Severity)Enum.Parse(typeof(webservice.Severity), logEntry.Severity.ToString()); wsLogEntry.Title = logEntry.Title; wsLogEntry.ExtendedProperties = WSLogEntry.ToJaggedArray((Hashtable)logEntry.ExtendedProperties); ws.Log(wsLogEntry); } catch (Exception e) { logEntry.AddErrorMessage(SR.SinkFailure(e.ToString())); throw; } catch { logEntry.AddErrorMessage(SR.SinkFailure(SR.UnknownError)); } } }
/// <summary> /// Iterates through each entry in the dictionary and display the key and/or value. /// </summary> /// <param name="tokenTemplate">Template to repeat for each key/value pair.</param> /// <param name="log">Log entry containing the extended properties dictionary.</param> /// <returns>Repeated template for each key/value pair.</returns> public override string FormatToken(string tokenTemplate, LogEntry log) { StringBuilder dictionaryBuilder = new StringBuilder(); foreach (KeyValuePair<string, object> entry in log.ExtendedProperties) { StringBuilder singlePair = new StringBuilder(tokenTemplate); string keyName = ""; if (entry.Key != null) { keyName = entry.Key.ToString(); } singlePair.Replace(DictionaryKeyToken, keyName); string keyValue = ""; if (entry.Value != null) { keyValue = entry.Value.ToString(); } singlePair.Replace(DictionaryValueToken, keyValue); dictionaryBuilder.Append(singlePair.ToString()); } return dictionaryBuilder.ToString(); }
/// <summary> /// Writes trace input to <see cref="Log.Write" />. /// </summary> /// <remarks>This is the method into which all TraceListener Write methods call.</remarks> private static void LogWrite(object o, string category = null) { if (RecursionCounter.Depth > 0) { return; } using (RecursionCounter.Enter()) { LogEntry logEntry; var d = o as Delegate; if (d != null) { logEntry = new LogEntry(d.DynamicInvoke(), d.GetAnonymousMethodInfo()); } else if (o is LogEntry) { logEntry = (LogEntry) o; } else { logEntry = new LogEntry(o); } logEntry.Category = category; Log.Write(logEntry); } }
/// <summary> /// Format a log entry as it should be written to the file /// </summary> /// <param name="entry">Entry to format</param> /// <returns> /// Formatted entry /// </returns> protected override string FormatLogEntry(LogEntry entry) { string result; var ex = entry.Exception; // to satisfy code contracts if (ex != null) { result= string.Format("{0} {1} {2} {3} {4} {5}\r\n{6}\r\n", entry.CreatedAt.ToString(Configuration.DateTimeFormat), entry.LogLevel.ToString().PadRight(8, ' '), entry.ThreadId.ToString("000"), FormatUserName(entry.UserName, 16).PadRight(16), FormatStackTrace(entry.StackFrames, 40).PadRight(40), FormatMessage(entry.Message), FormatException(ex, 1) ); } else { result= string.Format("{0} {1} {2} {3} {4} {5}\r\n", entry.CreatedAt.ToString(Configuration.DateTimeFormat), entry.LogLevel.ToString().PadRight(8, ' '), entry.ThreadId.ToString("000"), FormatUserName(entry.UserName, 16).PadRight(16), FormatStackTrace(entry.StackFrames, 40).PadRight(40), FormatMessage(entry.Message) ); } // do make Code Contracts shut up. return string.IsNullOrEmpty(result) ? "Invalid entry" : result; }
protected ConsoleColor GetColorByEntry(LogEntry logEntry) { if(!this.UseColor) return Console.ForegroundColor; switch(logEntry.LogType) { case LogEntry.LogTypes.Debug: return ConsoleColor.DarkGray; break; case LogEntry.LogTypes.Error: return XConsole.XConsole.ErrorColor; break; case LogEntry.LogTypes.Exception: return XConsole.XConsole.ErrorColor; break; case LogEntry.LogTypes.Fatal: return XConsole.XConsole.ErrorColor; break; case LogEntry.LogTypes.Success: return XConsole.XConsole.SuccessColor; break; case LogEntry.LogTypes.Warn: return XConsole.XConsole.WarningColor; break; } return Console.ForegroundColor; }
public void ApplyResolvesClientIpAddress() { var lookup = new Mock<IIpLookupService>(); var target = new GeoLookupTransformation(lookup.Object); string cIpAddress = "myClientIp"; string sIpAddress = "myServerIp"; var entry = new LogEntry { cIp = cIpAddress, sIp = sIpAddress, }; lookup.Setup(l => l.GetCountry(It.IsAny<string>())).Returns(new Country(TestCountryCode, TestCountryName)); target.Apply(entry); Assert.Equal(TestCountryName, entry.CountryName); Assert.Equal(TestCountryCode, entry.CountryCode); lookup.Verify(l => l.GetCountry(sIpAddress), Times.Never()); lookup.Verify(l => l.GetCountry(cIpAddress), Times.AtLeastOnce()); }
public void WhenLogging_ThenLogWriterWritesToTheInjectedStack() { var logEntry = new LogEntry() { Message = "message" }; this.logWriter.Write(logEntry); Assert.AreSame(logEntry, this.traceListener.tracedData); }
public void Debug(string format) { LastMessage = new LogEntry { Format = format, }; }
void ILogOutput.Write(LogEntry entry) { if (entry.Type == LogMessageType.Error) this.lastErrorMessage = entry.Message; else if (entry.Type == LogMessageType.Warning) this.lastWarningMessage = entry.Message; }
public override void Write(LogEntry entry) { string caller; if (UseStackFrame) { var frame = GetStackFrame(); caller = frame.GetMethod().ReflectedType.Name + "." + frame.GetMethod().Name + "():" + frame.GetFileLineNumber(); } else { caller = LoggedType.Namespace ?? ""; } var color = Console.ForegroundColor; Console.ForegroundColor = GetColor(entry.LogLevel); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + caller.PadRight(50) + entry.LogLevel.ToString().PadRight(10) + entry.Message); if (entry.Exception != null) { var sb = new StringBuilder(); BuildExceptionDetails(entry.Exception, 4, sb); Console.WriteLine(sb.ToString()); } Console.ForegroundColor = color; }
/// <summary> /// Calls when an log entry popped /// </summary> /// <param name="sender">The event sender</param> /// <param name="entry">The log entry</param> private void OnLogEntryPopped(object sender, LogEntry entry) { var content = LoggerContext.Current.Formatter.Apply(entry); if (!EventLog.SourceExists(entry.Application)) { EventLog.CreateEventSource(entry.Application, entry.Application); } EventLogEntryType entryType; switch (entry.Severity) { case LogLevel.Fatal: case LogLevel.Error: entryType = EventLogEntryType.Error; break; case LogLevel.Warning: entryType = EventLogEntryType.Warning; break; default: entryType = EventLogEntryType.Information; break; } EventLog.WriteEntry(entry.Application, entry.Message, entryType); }
public void Write(LogEntry entry) { if (Enabled) { FileStreamWriter.Write(Serializer.Serialize(entry)); } }
public void LogEntry_InnerException_DetailsFromInnerException() { const string InnerExceptionMessage = "() Inner exception message."; const string OuterExceptionMessage = ")( Outer exception message."; try { try { throw new Exception(InnerExceptionMessage); } catch (Exception innerException) { throw new Exception(OuterExceptionMessage, innerException); } } catch (Exception outerException) { var logEntry = new LogEntry( LogType.Error, "test", outerException, null); Assert.AreEqual(InnerExceptionMessage, logEntry.ExceptionMessage); } }
/// <summary> /// The internal log function. Every public logging method /// feeds into this function /// </summary> /// <param name="logEntry">The log entry</param> public override void Log(LogEntry logEntry) { if (LogFunction != null) { LogFunction(logEntry); } }
public void LogEntrySerialiseDeserialise() { var originalLogEntry = new LogEntry() { Timestamp = DateTime.UtcNow, Status = LogStatus.Fatal, GroupKey = Guid.NewGuid(), TargetKey = Guid.NewGuid(), InstanceKey = Guid.NewGuid(), LogContent = "Test Log Entry", }; LogEntry secondLogEntry; using (var stream = originalLogEntry.Serialise()) { secondLogEntry = new LogEntry(stream); } Assert.AreEqual(originalLogEntry.Timestamp, secondLogEntry.Timestamp); Assert.AreEqual(originalLogEntry.Status, secondLogEntry.Status); Assert.AreEqual(originalLogEntry.GroupKey, secondLogEntry.GroupKey); Assert.AreEqual(originalLogEntry.TargetKey, secondLogEntry.TargetKey); Assert.AreEqual(originalLogEntry.InstanceKey, secondLogEntry.InstanceKey); Assert.AreEqual(originalLogEntry.LogContent, secondLogEntry.LogContent); }
/// <summary> /// Enqueue to be written /// </summary> /// <param name="entry"></param> /// <remarks> /// The entry might be written directly in the same thread or enqueued to be written /// later. It's up to each implementation to decide. Keep in mind that a logger should not /// introduce delays in the thread execution. If it's possible that it will delay the thread, /// enqueue entries instead and write them in a seperate thread. /// </remarks> public void Enqueue(LogEntry entry) { var method = entry.GetLoggerInfo(); var tmp = String.Format("{0} {1} {2} {3} {4}", entry.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss.fff"), entry.ThreadId.ToString().PadLeft(3), entry.UserName.PadRight(25), method.PadRight(40), entry.Message.Replace("\r\n", "\r\n\t")); Console.ForegroundColor = GetColor(entry); Console.WriteLine(tmp); if (entry.Exception != null) { var exception = entry.Exception; var tabs = "\t"; while (exception != null) { Console.WriteLine(tabs + entry.Exception.ToString().Replace("\r\n", "\r\n" + tabs)); exception = exception.InnerException; tabs += "\t"; } } Console.ForegroundColor = ConsoleColor.Gray; }
public object[] MessageMarkup(LogEntry logEntry, int index) { if (!logEntry.Message.Contains("\n")) { string encodedMessage = EncodeXml10InvalidCharacters(logEntry.Message); return new object[] { encodedMessage }; } string[] lines = EncodeXml10InvalidCharacters(logEntry.Message).Trim().Split('\n'); if (lines.Length < 7) { return new object[] { new XElement("pre", EncodeXml10InvalidCharacters(logEntry.Message.Replace("\n", ""))) }; } return new object[] { PreTag(lines, 0, 2), new XElement("a", new XAttribute("id", "a" + index), new XAttribute("href", "#"), new XAttribute("onclick", string.Format("document.getElementById('log{0}').style.display = 'block';document.getElementById('a{0}').style.display = 'none'", index)), new XAttribute("class", "expandCode"), ". . ."), PreTag(lines, 2, lines.Length - 4, new XAttribute("id", "log" + index), new XAttribute("style", "display:none;")), PreTag(lines, lines.Length - 2, 2) }; }
public void Enqueue(LogEntry entry) { if (Filters.Any(f => !f.CanLog(entry))) return; Entries.Add(entry); }
public void Write(LogEntry entry) { using (OleDbConnection conn = new OleDbConnection(connStr)) { using (OleDbCommand cmd = conn.CreateCommand()) { cmd.CommandText = @" INSERT INTO [Request] (Date, Method, URL, Referral, ASPNETSessionID, UserHost, UserAddress, UserAgent) VALUES (@Date, @Method, @URL, @Referral, @ASPNETSessionID, @UserHost, @UserAddress, @UserAgent) "; cmd.Parameters.Add("@Date", entry.Date); cmd.Parameters.Add("@Method", entry.Method); cmd.Parameters.Add("@URL", Convert.ToString(entry.Url)); cmd.Parameters.Add("@Referral", Convert.ToString(entry.Referral)); cmd.Parameters.Add("@ASPNETSessionID", entry.ASPNETSessionID); cmd.Parameters.Add("@UserHost", entry.UserHost); cmd.Parameters.Add("@UserAddress", entry.UserAddress); cmd.Parameters.Add("@UserAgent", entry.UserAgent); conn.Open(); cmd.ExecuteNonQuery(); } } }
void SendLogEntry(WmiTraceListener listener, LogEntry logEntry) { ManagementScope scope = new ManagementScope(@"\\." + wmiPath); scope.Options.EnablePrivileges = true; StringBuilder sb = new StringBuilder("SELECT * FROM "); sb.Append("LogEntryV20"); string query = sb.ToString(); EventQuery eq = new EventQuery(query); using (ManagementEventWatcher watcher = new ManagementEventWatcher(scope, eq)) { watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived); watcher.Start(); LogSource source = new LogSource("notfromconfig", SourceLevels.All); source.Listeners.Add(listener); source.TraceData(TraceEventType.Error, 1, logEntry); BlockUntilWMIEventArrives(); watcher.Stop(); } }
public override void Write(LogEntry entry) { EventLogEntryType type; switch (entry.Level) { case Level.Debug: case Level.Trace: case Level.Info: type = EventLogEntryType.Information; break; case Level.Warn: type = EventLogEntryType.Warning; break; case Level.Error: case Level.Fatal: type = EventLogEntryType.Error; break; default: type = EventLogEntryType.Information; break; } using (var eventLog = new EventLog { Source = EventLogSource ?? entry.Source }) { var fmt = EntryFormatter ?? entry.Logger.LogManager.GetFormatter<string>(); var msg = fmt.Convert(entry); eventLog.WriteEntry(msg, type); } }
private void AddEntryToTree(LogEntry aEntry) { DateTime local = aEntry.DateTime.ToLocalTime(); TreeNode node = AddDate(local); TreeNode entry = GetOrAdd(node.Nodes, local.ToString("H:mm.ss")); entry.Tag = aEntry; }
public void Log <TEntity>(LogEntry <TEntity> logEntry) { _logsCollection.InsertOne(logEntry); }
private bool IsLogEntryTypeMatch(LogEntryTypeDescriptor descriptor, LogEntry logEntry) => (descriptor, logEntry) switch { (PropertyChangeLogEntryTypeDescriptor pcletd, _) when(logEntry.Changes.Any(c => c.Name == pcletd.PropertyName && (pcletd.TargetValue == null || pcletd.TargetValue == c.NewValue))) => true, _ => false, };
public override T GetResult(LogEntry entry) { return(ResultHandler(entry, entry.Text.RegexMatches(Regex))); }
private string GetFormatTemplate(IEnumerable <LogEntryTypeDescriptor> logEntryTypeDescriptors, LogEntry logEntry) { string result = "✍ Change at {date} by {user} with comment: {comment}"; foreach (var descriptor in logEntryTypeDescriptors) { if (IsLogEntryTypeMatch(descriptor, logEntry)) { result = CreateTemplate(descriptor); break; } } return(result); }
public override bool IsMatch(LogEntry entry) { return(base.IsMatch(entry) && Check(entry)); }
/// <summary> /// Formats a log entry and return a string to be outputted. /// </summary> /// <param name="log">Log entry to format.</param> /// <returns>A string representing the log entry.</returns> public abstract string Format(LogEntry log);