Пример #1
0
 public static void LogException(string title, string sub, System.Exception ex)
 {
     if (LogWriter == null || !UseLog)
     {
         return;
     }
     LogFormat(title, sub, true, ("Exception", ex.Message));
 }
Пример #2
0
        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();
                }
            }
        }
Пример #3
0
 static LogFormat LoadFormat(string filename)
 {
     using (var stream = System.IO.File.OpenRead(filename))
     {
         return(LogFormat.FromXML(stream));
     }
 }
Пример #4
0
 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));
 }
Пример #7
0
        /// <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);
        }
Пример #8
0
        /// <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);
        }
Пример #9
0
        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));
        }
Пример #10
0
 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));
 }
Пример #11
0
 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));
 }
Пример #12
0
        /// <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));
        }
Пример #13
0
        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);
            }
        }
Пример #14
0
        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));
        }
Пример #15
0
        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);
        }
Пример #16
0
 public StreamingLogger(string category, Stream outputStream, LogFormat format, LogLevel?logLevel)
 {
     _outputStream = outputStream;
     _categoryName = category;
     _logFormat    = format;
     _logLevel     = logLevel;
 }
Пример #17
0
        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);
        }
Пример #18
0
 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));
 }
Пример #19
0
        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));
            }
        }
Пример #20
0
        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);
            }));
        }
Пример #21
0
        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;
            }
        }
Пример #22
0
        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));
        }
Пример #23
0
        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());
            }
        }
Пример #25
0
        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));
        }
Пример #26
0
    public static LogBase CreateLogInstanceFromFile
        (string filename, LogFormat format)
    {
        LogBase logInstance = LogBase.CreateLogInstance(format);

        logInstance.ReadFile(filename);
        return(logInstance);
    }
Пример #27
0
 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... */ }
 }
Пример #28
0
 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... */ }
 }
Пример #29
0
 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... */ }
 }
Пример #30
0
        public static void WriteToLog(string Text, LogFormat Format)
        {
            ConsoleColor OldColor = Console.ForegroundColor;

            Console.ForegroundColor = Format.Color;
            Console.WriteLine(Format.Header + Text);
            Console.ForegroundColor = OldColor;
        }
Пример #31
0
    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;
    }
Пример #32
0
 public static LogBase CreateLogInstanceFromFile(string filename, LogFormat format)
 {
     LogBase logInstance = LogBase.CreateLogInstance(format);
     logInstance.ReadFile(filename);
     return logInstance;
 }
Пример #33
0
        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();
        }
Пример #34
0
    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;
    }
Пример #35
0
 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;
 }