public static void LogException(string title, string sub, System.Exception ex) { if (LogWriter == null || !UseLog) { return; } LogFormat(title, sub, true, ("Exception", ex.Message)); }
private void load_log_formats() { if (this.master_ == null) { this.master_ = (CUTS.Master) this.Page.Master; } try { // Open the connection to the database. if (this.database_.State == ConnectionState.Closed) { this.database_.Open(); } // Select the log formats from the table. DbDataReader reader = this.database_.SelectLogFormatReader(); try { if (reader.HasRows) { // Get the ordinals of the columns in the table. int lfid = reader.GetOrdinal("lfid"); int lfmt = reader.GetOrdinal("lfmt"); LogFormat lf; while (reader.Read()) { // Create a new log format. lf = new LogFormat(reader.GetInt32(lfid), reader.GetString(lfmt)); // Insert the log format into the manager. this.lf_manager_.Add(lf); } } } finally { // Make sure the reader is closed. if (!reader.IsClosed) { reader.Close(); } } } catch (Exception ex) { this.master_.Console.Add(ex); } finally { // Make sure the database collection if closed. if (this.database_.State == ConnectionState.Open) { this.database_.Close(); } } }
static LogFormat LoadFormat(string filename) { using (var stream = System.IO.File.OpenRead(filename)) { return(LogFormat.FromXML(stream)); } }
private bool TryGetValue(object obj, object[] indices, out object value) { try { value = this.targetProperty.GetValue(obj, indices); return(true); } catch (Exception e) { if (e is TargetInvocationException) { e = e.InnerException; } if (indices != null && indices.Length > 0) { Logs.Editor.WriteError( "An error occurred trying to get property {0}.{1}[{2}]: {3}", LogFormat.Type(this.targetProperty.DeclaringType), this.targetProperty.Name, indices.ToString(", "), LogFormat.Exception(e)); } else { Logs.Editor.WriteError( "An error occurred trying to get property {0}.{1}: {2}", LogFormat.Type(this.targetProperty.DeclaringType), this.targetProperty.Name, LogFormat.Exception(e)); } value = null; return(false); } }
public Task LogsDefaultLevelFallbackActionTest(TargetFrameworkMoniker tfm, LogFormat logFormat) { return(ValidateLogsActionAsync( new LogsConfiguration() { FilterSpecs = new Dictionary <string, LogLevel?>() { { TestAppScenarios.Logger.Categories.LoggerCategory1, LogLevel.Error }, { TestAppScenarios.Logger.Categories.LoggerCategory2, null }, { TestAppScenarios.Logger.Categories.LoggerCategory3, LogLevel.Warning } }, LogLevel = LogLevel.Information, UseAppFilters = false }, async reader => { LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1CriticalEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2InformationEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2CriticalEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3CriticalEntry, await reader.ReadAsync()); Assert.False(await reader.WaitToReadAsync()); }, logFormat, tfm)); }
public Task LogsUseAppFiltersViaBodyActionTest(TargetFrameworkMoniker tfm, LogFormat logFormat) { return(ValidateLogsActionAsync( new LogsConfiguration() { LogLevel = LogLevel.Trace, UseAppFilters = true }, async reader => { LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1DebugEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1InformationEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1CriticalEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2InformationEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2CriticalEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3CriticalEntry, await reader.ReadAsync()); Assert.False(await reader.WaitToReadAsync()); }, logFormat, tfm)); }
/// <summary>在发生异常时调用。</summary> /// <param name="filterContext">操作筛选器上下文。</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="filterContext" /> 参数为 null。</exception> public override void OnException(ExceptionContext filterContext) { var context = filterContext.HttpContext; var exception = filterContext.Exception; if (!filterContext.ExceptionHandled) { LogMessage logMessage = new LogMessage { OperationTime = DateTime.Now, Url = context.Request.RawUrl, Ip = context.Request.UserHostAddress, Host = context.Request.UserHostName, Browser = context.Request.Browser.Browser, UserAgent = context.Request.UserAgent, ExceptionInfo = exception.InnerException == null ? exception.Message : exception.InnerException.Message, ExceptionSource = exception.Source, ExceptionRemark = exception.StackTrace }; string strMessage = LogFormat.ExceptionFormat(logMessage); _logHelper.Error(strMessage); filterContext.ExceptionHandled = true; } filterContext.Result = new ContentResult { Content = new BaseJsonResult <string> { Status = (int)JsonObjectStatus.Error, Message = exception.Message }.TryToJson() }; //base.OnException(filterContext); }
/// <summary> /// 写入日志(log4net) /// </summary> /// <param name="context">提供使用</param> private void WriteLog(ExceptionContext context) { if (context == null) { return; } if (OperatorProvider.Provider.Current() == null) { return; } if (OperatorProvider.Provider.IsOverdue()) { return; } var log = LogFactory.GetLogger(context.Controller.ToString()); Exception Error = context.Exception; LogMessage logMessage = new LogMessage(); logMessage.OperationTime = DateTime.Now; logMessage.Url = HttpContext.Current.Request.RawUrl; logMessage.Class = context.Controller.ToString(); logMessage.Ip = Net.Ip; logMessage.Host = Net.Host; logMessage.Browser = Net.Browser; if (null != OperatorProvider.Provider.Current()) { logMessage.UserName = OperatorProvider.Provider.Current().Account + "(" + OperatorProvider.Provider.Current().UserName + ")"; } //if (Error.InnerException == null) //{ // logMessage.ExceptionInfo = Error.Message; //} //else //{ // logMessage.ExceptionInfo = Error.InnerException.Message; //} logMessage.ExceptionInfo = Newtonsoft.Json.JsonConvert.SerializeObject(Error); //logMessage.ExceptionSource = Error.Source; //logMessage.ExceptionRemark = Error.StackTrace; string strMessage = new LogFormat().ExceptionFormat(logMessage); log.Error(strMessage); LogEntity logEntity = new LogEntity(); logEntity.CategoryId = 4; logEntity.OperateTypeId = ((int)OperationType.Exception).ToString(); logEntity.OperateType = EnumAttribute.GetDescription(OperationType.Exception); logEntity.OperateAccount = logMessage.UserName; if (null != OperatorProvider.Provider.Current()) { logEntity.OperateUserId = OperatorProvider.Provider.Current().UserId; } logEntity.ExecuteResult = -1; logEntity.ExecuteResultJson = strMessage; logEntity.Module = SystemInfo.CurrentModuleName; logEntity.ModuleId = SystemInfo.CurrentModuleId; logEntity.WriteLog(); //SendMail(strMessage); }
public Task LogsAllCategoriesTest(DiagnosticPortConnectionMode mode, LogFormat logFormat) { return(ValidateLogsAsync( mode, LogLevel.Trace, async reader => { // Default LogLevel.Trace is converted to EventLevel.LogAlways but // runtime does not translate that back to LogLevel.Trace however it // falls back to capturing LogLevel.Debug and above. Thus, no Trace // events will ever be collected if relying on default log level. //LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1TraceEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1DebugEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1InformationEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1CriticalEntry, await reader.ReadAsync()); //LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2TraceEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2DebugEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2InformationEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2CriticalEntry, await reader.ReadAsync()); //LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3TraceEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3DebugEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3InformationEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3CriticalEntry, await reader.ReadAsync()); Assert.False(await reader.WaitToReadAsync()); }, logFormat)); }
public Task LogsWildcardTest(DiagnosticPortConnectionMode mode, LogFormat logFormat) { return(ValidateLogsAsync( mode, new LogsConfiguration() { FilterSpecs = new Dictionary <string, LogLevel?>() { { "*", LogLevel.Trace }, { TestAppScenarios.Logger.Categories.LoggerCategory2, LogLevel.Warning } }, LogLevel = LogLevel.Information, UseAppFilters = false }, async reader => { LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1TraceEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1DebugEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1InformationEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1CriticalEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2CriticalEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3TraceEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3DebugEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3InformationEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3CriticalEntry, await reader.ReadAsync()); Assert.False(await reader.WaitToReadAsync()); }, logFormat)); }
public Task LogsUseAppFiltersViaBodyTest(DiagnosticPortConnectionMode mode, LogFormat logFormat) { return(ValidateLogsAsync( mode, new LogsConfiguration() { LogLevel = LogLevel.Trace, UseAppFilters = true }, async reader => { LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1DebugEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1InformationEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category1CriticalEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2InformationEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category2CriticalEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3WarningEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3ErrorEntry, await reader.ReadAsync()); LogsTestUtilities.ValidateEntry(LogsTestUtilities.Category3CriticalEntry, await reader.ReadAsync()); Assert.False(await reader.WaitToReadAsync()); }, logFormat)); }
/// <summary> /// Prepares an object for serialization and generates its header information. /// </summary> /// <param name="obj">The object to write</param> protected ObjectHeader PrepareWriteObject(object obj) { Type objType = obj.GetType(); SerializeType objSerializeType = GetSerializeType(objType); DataType dataType = objSerializeType.DataType; uint objId = 0; // Check whether it's going to be an ObjectRef or not if (objSerializeType.CanBeReferenced) { bool newId; objId = this.idManager.Request(obj, out newId); // If its not a new id, write a reference if (!newId) { dataType = DataType.ObjectRef; } } // Check whether the object is expected to be serialized if (dataType != DataType.ObjectRef && !objSerializeType.IsSerializable && !typeof(ISerializeExplicit).GetTypeInfo().IsAssignableFrom(objSerializeType.Type) && objSerializeType.Surrogate == null) { this.LocalLog.WriteWarning("Ignoring object of Type '{0}' which is flagged with the {1}.", LogFormat.Type(objSerializeType.Type), typeof(DontSerializeAttribute).Name); return(null); } // Generate object header information return(new ObjectHeader(objId, dataType, objSerializeType)); }
public static LogEntryStrackFrame FromStackFrame(StackFrame stackFrame) { if (stackFrame == null) { return(Empty); } try { LogEntryStrackFrame result = new LogEntryStrackFrame(); result._rawStackFrame = LogFormat.StackFrame(stackFrame); result._fileName = stackFrame.GetFileName(); result._lineNumber = stackFrame.GetFileLineNumber(); MethodBase method = stackFrame.GetMethod(); if (method != null) { result._declaringTypeName = method.DeclaringType.FullName; result._methodName = method.Name; result._methodSignatureHash = GetMethodSignatureHash(method); } return(result); } catch (Exception e) { LogEntryStrackFrame result = new LogEntryStrackFrame(); result._rawStackFrame = "Error: " + e.GetType().Name; return(result); } }
public string WriteExceptionLog(string modelName, string userName, string mac, string message, string message2) { var log = LogFactory.GetLogger(modelName); LogMessage logMessage = new LogMessage(); logMessage.OperationTime = DateTime.Now; if (!string.IsNullOrEmpty(userName)) { logMessage.UserName = userName; } logMessage.Url = this.Request.Url; logMessage.Class = this.ToString(); logMessage.Host = this.Request.Headers.Host; if (!string.IsNullOrEmpty(mac)) { logMessage.Ip = mac; } logMessage.Content = message; string strMessageInfo = new LogFormat().InfoFormat(logMessage); log.Error(strMessageInfo); ResponseModule res = new ResponseModule(); res.code = "500"; res.message = message2; return(Json.ToJson(res)); }
private MemberInfo ReadMemberInfo(ObjectHeader header) { MemberInfo result = null; try { if (header.DataType == DataType.Type) { string typeString = this.reader.ReadString(); Type type = this.ResolveType(typeString, header.ObjectId); result = (type != null) ? type.GetTypeInfo() : null; } else { string memberString = this.reader.ReadString(); result = this.ResolveMember(memberString, header.ObjectId); } } catch (Exception e) { result = null; this.LocalLog.WriteError( "An error occurred in deserializing MemberInfo object Id {0} of type '{1}': {2}", header.ObjectId, LogFormat.Type(header.DataType.ToActualType()), LogFormat.Exception(e)); } // Prepare object reference this.idManager.Inject(result, header.ObjectId); return(result); }
public StreamingLogger(string category, Stream outputStream, LogFormat format, LogLevel?logLevel) { _outputStream = outputStream; _categoryName = category; _logFormat = format; _logLevel = logLevel; }
private PackageUpdateSchedule PrepareUpdateSchedule() { // Load existing update schedule in order to extend it string updateFilePath = this.env.UpdateFilePath; PackageUpdateSchedule updateSchedule = null; if (File.Exists(updateFilePath)) { try { updateSchedule = PackageUpdateSchedule.Load(updateFilePath); } catch (Exception exception) { updateSchedule = null; Logs.Editor.WriteError("Error parsing existing package update schedule '{0}': {1}", Path.GetFileName(updateFilePath), LogFormat.Exception(exception)); } } // If none existed yet, create a fresh update schedule if (updateSchedule == null) { updateSchedule = new PackageUpdateSchedule(); } return(updateSchedule); }
public bool Equals(ApplicationSetting other) { return (SkipFirstBlankRows == other.skipFirstBlankRows && SkipFirstBlankColumns == other.SkipFirstBlankColumns && TrimLastBlankRows == other.TrimLastBlankRows && TrimLastBlankColumns == other.TrimLastBlankColumns && ExternalCommands.SequenceEqual(other.ExternalCommands) && FileSettings.SequenceEqual(other.FileSettings) && RecentFileSets.SequenceEqual(other.RecentFileSets) && CellWidth == other.cellWidth && AlternatingColorStrings.SequenceEqual(other.AlternatingColorStrings) && ColumnHeaderColorString.Equals(other.ColumnHeaderColorString) && RowHeaderColorString.Equals(other.RowHeaderColorString) && AddedColorString.Equals(other.AddedColorString) && RemovedColorString.Equals(other.RemovedColorString) && ModifiedColorString.Equals(other.ModifiedColorString) && ModifiedRowColorString.Equals(other.ModifiedRowColorString) && ColorModifiedRow.Equals(other.ColorModifiedRow) && SearchHistory.Equals(other.SearchHistory) && FontName.Equals(other.FontName) && LogFormat.Equals(other.LogFormat) && AddedRowLogFormat.Equals(other.AddedRowLogFormat) && RemovedRowLogFormat.Equals(other.RemovedRowLogFormat)); }
private static void ArchiveOldLogfile() { try { // If there is an existing logfile, archive it for diagnostic purposes FileInfo prevLogfile = new FileInfo(DualityEditorApp.EditorLogfilePath); if (prevLogfile.Exists) { if (!Directory.Exists(DualityEditorApp.EditorPrevLogfileDir)) { Directory.CreateDirectory(DualityEditorApp.EditorPrevLogfileDir); } string timestampToken = prevLogfile.LastWriteTimeUtc.ToString("yyyy-MM-dd-T-HH-mm-ss"); string prevLogfileName = string.Format(DualityEditorApp.EditorPrevLogfileName, timestampToken); string prevLogFilePath = Path.Combine(DualityEditorApp.EditorPrevLogfileDir, prevLogfileName); prevLogfile.MoveTo(prevLogFilePath); } } catch (Exception e) { Logs.Core.WriteWarning("Unable to archive old logfile: {0}", LogFormat.Exception(e)); } }
public Task <ActionResult> Logs( ProcessFilter?processFilter, [FromQuery][Range(-1, int.MaxValue)] int durationSeconds = 30, [FromQuery] LogLevel level = LogLevel.Debug) { TimeSpan duration = ConvertSecondsToTimeSpan(durationSeconds); return(this.InvokeService(async() => { IProcessInfo processInfo = await _diagnosticServices.GetProcessAsync(processFilter, HttpContext.RequestAborted); LogFormat format = ComputeLogFormat(Request.GetTypedHeaders().Accept); if (format == LogFormat.None) { return this.NotAcceptable(); } string contentType = (format == LogFormat.EventStream) ? ContentTypeEventStream : ContentTypeNdJson; string downloadName = (format == LogFormat.EventStream) ? null : FormattableString.Invariant($"{GetFileNameTimeStampUtcNow()}_{processInfo.ProcessId}.txt"); return new OutputStreamResult(async(outputStream, token) => { await _diagnosticServices.StartLogs(outputStream, processInfo, duration, format, level, token); }, contentType, downloadName); })); }
static private void _Write(string a, string s, LogFormat logFormat = LogFormat.Normal) { switch (logFormat) { case LogFormat.Normal: Debug.LogFormat($"{a} {s}"); break; case LogFormat.Warning: Debug.LogWarningFormat($"{a} {s}"); break; case LogFormat.Error: Debug.LogErrorFormat($"{a} {s}"); break; case LogFormat.Screen: if (KerbalismAPI.KerbalismInstalled) { KerbalismAPI.Message(s); } else { ScreenMessages.PostScreenMessage(s, 3.0f, ScreenMessageStyle.LOWER_CENTER, false); } break; } }
public Task <ActionResult> CaptureLogs( ProcessKey?processKey, [FromQuery][Range(-1, int.MaxValue)] int durationSeconds = 30, [FromQuery] LogLevel?level = null, [FromQuery] string egressProvider = null) { return(InvokeForProcess(processInfo => { TimeSpan duration = ConvertSecondsToTimeSpan(durationSeconds); LogFormat format = ComputeLogFormat(Request.GetTypedHeaders().Accept); if (format == LogFormat.None) { return this.NotAcceptable(); } string fileName = FormattableString.Invariant($"{GetFileNameTimeStampUtcNow()}_{processInfo.EndpointInfo.ProcessId}.txt"); string contentType = format == LogFormat.EventStream ? ContentTypes.TextEventStream : ContentTypes.ApplicationNdJson; Func <Stream, CancellationToken, Task> action = async(outputStream, token) => { using var loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(new StreamingLoggerProvider(outputStream, format, level)); var settings = new EventLogsPipelineSettings() { Duration = duration }; //If the user does not explicitly specify a log level, we will use the apps defaults for .net 5. //Otherwise, we use the log level specified by the query. if ((!level.HasValue) && (processInfo.EndpointInfo.RuntimeInstanceCookie != Guid.Empty)) { settings.UseAppFilters = true; } else { settings.LogLevel = level.GetValueOrDefault(LogLevel.Warning); } var client = new DiagnosticsClient(processInfo.EndpointInfo.Endpoint); await using EventLogsPipeline pipeline = new EventLogsPipeline(client, settings, loggerFactory); await pipeline.RunAsync(token); }; return Result( ArtifactType_Logs, egressProvider, action, fileName, contentType, processInfo.EndpointInfo, format != LogFormat.EventStream); }, processKey, ArtifactType_Logs)); }
private static System.Collections.IEnumerable PackageOperationThread(ProcessingBigTaskDialog.WorkerInterface workerInterface) { PackageOperationData data = workerInterface.Data as PackageOperationData; workerInterface.Progress = -1.0f; if (data.Package.Version != null) { workerInterface.StateDesc = string.Format("Package '{0}', Version {1}...", data.Package.Id, data.Package.Version); } else { workerInterface.StateDesc = string.Format("Package '{0}'...", data.Package.Id); } yield return(null); try { data.Operation(data); } catch (Exception e) { Logs.Editor.WriteError("An error occurred while processing Package '{0}', Version {1}: {2}", data.Package.Id, data.Package.Version, LogFormat.Exception(e)); workerInterface.Error = e; } yield break; }
public void OnActionExecuted(ActionExecutedContext context) { _logRequest.ExcuteEndTime = DateTime.Now; if (context.Exception == null) { _logRequest.ResponseBodys = (context.Result as ObjectResult).Value.ToJson(); LogSuccess(); } else { Result result = null; if (context.Exception is ChecksException ce) //验证异常(业务) { result = Result.Fail(ce.Code, ce.Message); _logRequest.ResponseBodys = result.ToJson(); LogSuccess(); } else if (context.Exception is QueueException qe) //消息队列异常(业务) { result = Result.Fail(qe.Code, qe.Message); _logRequest.ResponseBodys = result.ToJson(); LogSuccess(); } else { _logRequest.ResponseBodys = context.Exception.ToString(); result = Result.Fail(500, "服务器连接错误"); Log.Error(LogFormat.Record("startupExpection", (_logRequest.ExcuteEndTime - _logRequest.ExcuteStartTime).Milliseconds, DateTime.Now, _logRequest)); } context.ExceptionHandled = true; context.Result = new ObjectResult(result.ToJson()); } }
protected override void Log(string message, params object[] formatParameters) { string formatted = String.Format(message, formatParameters); System.Diagnostics.Debug.WriteLine(LogFormat.Replace("{date}", DateTime.Now.ToString("yyyy-MM-dd")) .Replace("{time}", DateTime.Now.ToString("HH:mm:ss:fff")) .Replace("{message}", formatted)); }
public static LogBase CreateLogInstanceFromFile (string filename, LogFormat format) { LogBase logInstance = LogBase.CreateLogInstance(format); logInstance.ReadFile(filename); return(logInstance); }
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { Logs.Editor.WriteError(LogFormat.Exception(e.ExceptionObject as Exception)); } catch (Exception) { /* Ensure we're not causing any further exception by logging... */ } }
private void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { try { Logs.Editor.WriteError(LogFormat.Exception(e.Exception)); } catch (Exception) { /* Ensure we're not causing any further exception by logging... */ } }
private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { try { Logs.Editor.WriteError(LogFormat.Exception(e.Exception)); } catch (Exception) { /* Ensure we're not causing any further exception by logging... */ } }
public static void WriteToLog(string Text, LogFormat Format) { ConsoleColor OldColor = Console.ForegroundColor; Console.ForegroundColor = Format.Color; Console.WriteLine(Format.Header + Text); Console.ForegroundColor = OldColor; }
public static LogBase CreateLogInstance(LogFormat format) { LogBase logInstance = null; switch (format) { case LogFormat.GPRMC: logInstance = new LogGPRMC(); break; case LogFormat.OziExplorer: logInstance = new LogOziExplorer(); break; } return logInstance; }
public static LogBase CreateLogInstanceFromFile(string filename, LogFormat format) { LogBase logInstance = LogBase.CreateLogInstance(format); logInstance.ReadFile(filename); return logInstance; }
private void IISWebLogConfig(string siteName, string logPhysicalPath, LogFormat logFormat, bool isLocalTimeRollover) { Site site = _serverManager.Sites[siteName]; if (site == null) { throw new Exception(string.Format("站点{0}不存在!", siteName)); } SiteLogFile siteLog = site.LogFile; siteLog.LogFormat = LogFormat.W3c; siteLog.LocalTimeRollover = isLocalTimeRollover; siteLog.Directory = logPhysicalPath; _serverManager.CommitChanges(); }
public static LogFormat DetectLogFormatFromString(ref string dataString) { Hashtable dummyEntry = new Hashtable(); LogFormat format = LogFormat.Unknown; string[] lines = dataString.Split('\n'); foreach (string line in lines) { if (LogGPRMC.IsLogEntry(line, ref dummyEntry)) { format = LogFormat.GPRMC; break; } if (LogOziExplorer.IsLogEntry(line, ref dummyEntry)) { format = LogFormat.OziExplorer; break; } } return format; }
public string ToString(LogFormat format) { string result = string.Empty; if (format == LogFormat.XmlFile) { using (var ms = new MemoryStream()) { Serializer<LogItem>.Serialize(ms, this); ms.Seek(0, SeekOrigin.Begin); using (var sr = new StreamReader(ms)) { result = sr.ReadToEnd(); sr.Close(); } } } else if(format == LogFormat.PlainText) { if (this.IsNetworkLog) { result = string.Format("{0:u}:{1} To {2} With {3} Occur {4}", this.Time, this.Action, this.URL, this.Param, this.Message); } else { result = string.Format("{0:u}:{1}", this.Time, this.Message); } } return result; }