Beispiel #1
0
        private static void Main(string[] args)
        {
            Program.args = args;
            NLog.LogLevel info      = NLog.LogLevel.Info;
            string[]      strArrays = args;
            for (int i = 0; i < (int)strArrays.Length; i++)
            {
                if (strArrays[i] == "--debug")
                {
                    info = NLog.LogLevel.Debug;
                }
            }
            info = NLog.LogLevel.Debug;
            LoggingConfiguration loggingConfiguration = new LoggingConfiguration();
            string     directoryName            = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string     fileNameWithoutExtension = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location);
            FileTarget fileTarget = new FileTarget();

            loggingConfiguration.AddTarget("file", fileTarget);
            fileTarget.FileName        = Path.Combine(directoryName, string.Concat(fileNameWithoutExtension, ".log"));
            fileTarget.Layout          = "${longdate} | ${level:uppercase=true} | ${logger} | ${message}";
            fileTarget.MaxArchiveFiles = 0;
            LoggingRule loggingRule = new LoggingRule("*", info, fileTarget);

            loggingConfiguration.LoggingRules.Add(loggingRule);
            LogManager.Configuration = loggingConfiguration;
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Program.FCS_UnhandledException);
            Program.logger.Info("** Start **");
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new baseForm());
            Program.logger.Info("** Shutdown **");
        }
 private Microsoft.Extensions.Logging.LogLevel getAppropriate(NLog.LogLevel level)
 {
     if (level == NLog.LogLevel.Trace)
     {
         return(Microsoft.Extensions.Logging.LogLevel.Trace);
     }
     else if (level == NLog.LogLevel.Debug)
     {
         return(Microsoft.Extensions.Logging.LogLevel.Debug);
     }
     else if (level == NLog.LogLevel.Info)
     {
         return(Microsoft.Extensions.Logging.LogLevel.Information);
     }
     else if (level == NLog.LogLevel.Warn)
     {
         return(Microsoft.Extensions.Logging.LogLevel.Warning);
     }
     else if (level == NLog.LogLevel.Error)
     {
         return(Microsoft.Extensions.Logging.LogLevel.Error);
     }
     else if (level == NLog.LogLevel.Fatal)
     {
         return(Microsoft.Extensions.Logging.LogLevel.Critical);
     }
     else if (level == NLog.LogLevel.Off)
     {
         return(Microsoft.Extensions.Logging.LogLevel.None);
     }
     else
     {
         return(Microsoft.Extensions.Logging.LogLevel.None);
     }
 }
        public static void ConfigureViaCode(LogLevel consoleLogLevel, LogLevel fileLogLevel)
        {
            // Step 1. Create configuration object
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration
            var consoleTarget = new ConsoleTarget();
            config.AddTarget("console", consoleTarget);

            var fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);

            // Step 3. Set target properties
            consoleTarget.Layout = @"${message} ${onexception:EXCEPTION\:${exception:format=tostring}}";

            fileTarget.Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} [${level:uppercase=true}] ${message}  ${onexception:EXCEPTION\:${exception:format=tostring}}";
            fileTarget.FileName = "C:\\temp\\logs\\SpiderOpenQuant.${date:format=yyyy-MM-dd hh}.log";
            fileTarget.ConcurrentWrites = false;
            fileTarget.KeepFileOpen = true;
            fileTarget.OpenFileCacheTimeout = 60;

            // Step 4. Define rules
            var rule1 = new LoggingRule("*", consoleLogLevel, consoleTarget);
            config.LoggingRules.Add(rule1);

            var rule2 = new LoggingRule("*", fileLogLevel, fileTarget);
            config.LoggingRules.Add(rule2);

            // Step 5. Activate the configuration
            LogManager.Configuration = config;
        }
Beispiel #4
0
        public void LogInfo(NLog.LogLevel logLevel, string callingAssembly, Exception ex, int propertyId)
        {
            // Search with NLogConsole.Program
            String EnviromentDetails = "New240 Client ID : " + propertyId +
                                       "|| Class : " + callingAssembly.ToString() +
                                       " || Follwed By Environment Details";

            // var logfactory1 = new LogFactory();
            Console.WriteLine(guid);
            LogMessage logMessage = new LogMessage
            {
                RequestID = guid,
                Message   = EnviromentDetails
            };

            var entry = new LogEventInfo()
            {
                TimeStamp  = DateTime.UtcNow,
                Level      = logLevel,
                Message    = EnviromentDetails,
                LoggerName = "",
                Exception  = ex == null ? null : ex
            };

            foreach (var param in logMessage.GetType().GetProperties())
            {
                entry.Properties[param.Name] = param.GetValue(logMessage, null);
            }

            _logger.Log(typeof(Logger), entry);
        }
Beispiel #5
0
        private void InitialiseLogger(string filename, NLog.LogLevel logLevel)
        {
            try
            {
                LoggingConfiguration config = new LoggingConfiguration();
                string     fileTargetName   = "Log_File";
                FileTarget fileTarget       = new FileTarget();
                config.AddTarget(fileTargetName, fileTarget);

                fileTarget.Header = "====Header===Start time = ${longdate} Machine = ${machinename} Product version = ${gdc:item=version}\r\n";
                fileTarget.Footer = "====Footer===End time =${longdate} \r\n";

                fileTarget.FileName         = filename;
                fileTarget.ArchiveAboveSize = 5 * 1024 * 1024; // max file size - 5*1024*1024 = 5MB
                fileTarget.Layout           = "[Begin]${longdate} [${level}] ${callsite:includeSourcePath=true} ${message} ${exception:format=ToString,StackTrace} ${newline}";

                LoggingRule ruleFile = new LoggingRule("*", logLevel, fileTarget);
                config.LoggingRules.Add(ruleFile);
                LogManager.Configuration = config;

                this.mlog = LogManager.GetLogger(fileTargetName);
            }
            catch
            {
            }
        }
Beispiel #6
0
 private void DoLogFormat(NLog.LogLevel pLogLevel, string strFormat, params object[] args)
 {
     lock (obj)
     {
         this.logIns.Log(pLogLevel, strFormat, args);
     }
 }
Beispiel #7
0
        protected static Zidium.Api.LogLevel GetLogLevel(NLog.LogLevel level)
        {
            if (level.Ordinal >= NLog.LogLevel.Fatal.Ordinal)
            {
                return(Zidium.Api.LogLevel.Fatal);
            }

            if (level.Ordinal >= NLog.LogLevel.Error.Ordinal)
            {
                return(Zidium.Api.LogLevel.Error);
            }

            if (level.Ordinal >= NLog.LogLevel.Warn.Ordinal)
            {
                return(Zidium.Api.LogLevel.Warning);
            }

            if (level.Ordinal >= NLog.LogLevel.Info.Ordinal)
            {
                return(Zidium.Api.LogLevel.Info);
            }

            if (level.Ordinal >= NLog.LogLevel.Debug.Ordinal)
            {
                return(Zidium.Api.LogLevel.Debug);
            }

            return(Zidium.Api.LogLevel.Trace);
        }
Beispiel #8
0
        private LogEventInfo GetLogEvent(string loggerName, LogLevel level, Exception exception, string format, object[] args)
        {
            string assemblyProp     = string.Empty;
            string classProp        = string.Empty;
            string methodProp       = string.Empty;
            string messageProp      = string.Empty;
            string innerMessageProp = string.Empty;
            string stackTraceProp   = string.Empty;

            var logEvent = new LogEventInfo(
                level, loggerName, string.Format(format, args));

            if (exception != null)
            {
                assemblyProp   = exception.Source;
                classProp      = exception.TargetSite.DeclaringType.FullName;
                methodProp     = exception.TargetSite.Name;
                messageProp    = exception.Message;
                stackTraceProp = exception.StackTrace;

                if (exception.InnerException != null)
                {
                    innerMessageProp = exception.InnerException.Message;
                }
            }

            logEvent.Properties["error-source"]        = assemblyProp;
            logEvent.Properties["error-class"]         = classProp;
            logEvent.Properties["error-method"]        = methodProp;
            logEvent.Properties["error-message"]       = messageProp;
            logEvent.Properties["inner-error-message"] = innerMessageProp;
            logEvent.Properties["stack-trace"]         = stackTraceProp;

            return(logEvent);
        }
Beispiel #9
0
 public DicomParserLogger(Logger log, LogLevel level)
 {
     _log = log;
     _level = level;
     _depth = 0;
     _pad = String.Empty;
 }
Beispiel #10
0
        public void Compile(DroneEnv env, LogLevel logLevel)
        {
            if (this.IsRecompileNeeded(env.Config))
            {
                var result = this.CompileCore(env);

                try
                {
                    if (result.IsSuccess)
                    {
                        this.CreateCache(env.Config);
                        this.log.Log(logLevel, "compiled ({0})", HumanTime.Format(result.TimeElapsed));
                    }
                    else
                    {
                        throw DroneCompilerException.Get(result);
                    }
                }
                finally
                {
                    this.LogResult(result);
                }
            }
            else
            {
                this.log.Log(logLevel, "compiliation skipped, all files up to date");
            }
        }
Beispiel #11
0
        public static void Configure(LogLevel logLevel = null)
        {
            logLevel = logLevel ?? LogLevel.Info;

            // log layout format
            var layout = "${date:format=hh\\:mm\\:ss tt} ${pad:padding=6:inner=${level:uppercase=true}} ${message} ${exception:separator=\r\n:format=message,type,method,stackTrace:maxInnerExceptionLevel=10:innerExceptionSeparator=\r\n:innerFormat=message,type,method,stackTrace}";

            // initialize logging configuration
            var config = LogManager.Configuration ?? new LoggingConfiguration();

            // create console target
            if (!Debugger.IsAttached)
            {
                var consoleTarget = new ColoredConsoleTarget();
                consoleTarget.Layout = layout;
                config.AddTarget("console", consoleTarget);
                config.LoggingRules.Add(new LoggingRule("*", logLevel, consoleTarget));
            }
            else
            {
                var consoleTarget = new DebuggerTarget();
                consoleTarget.Layout = layout;
                config.AddTarget("console", consoleTarget);
                config.LoggingRules.Add(new LoggingRule("*", logLevel, consoleTarget));
            }

            // activate configuration and bind
            LogManager.Configuration = config;
        }
Beispiel #12
0
        public static NLogLoggingConfiguration UseMongoTarget(this NLogLoggingConfiguration nlogConf, IConfiguration configuration)
        {
            var targetOption = configuration.GetSection(nameof(NLogNoSqlTargetOptions)).Get <NLogNoSqlTargetOptions>();
            var mongoOption  = configuration.GetSection(nameof(LogStorageOptions)).Get <LogStorageOptions>();

            if (targetOption == null || mongoOption == null)
            {
                throw new NullReferenceException($"Cannot found {nameof(NLogNoSqlTargetOptions)} or {nameof(LogStorageOptions)} from configuration file!");
            }

            var mongoTarget = new MongoTarget()
            {
                Name             = targetOption.Name,
                CollectionName   = targetOption.CollectionName,
                ConnectionString = configuration["MongoDBConnection"],
                DatabaseName     = mongoOption.DatabaseName,
                IncludeDefaults  = true
            };

            nlogConf.AddTarget(mongoTarget);

            foreach (var r in targetOption.Rules)
            {
                var minlevel = LogLevel.FromString(r.MinLevel);
                var maxLevel = LogLevel.FromString(r.MaxLevel);
                nlogConf.AddRule(minlevel, maxLevel, mongoTarget, r.Logger);
            }

            return(nlogConf);
        }
Beispiel #13
0
 public static void LogHttpError(HttpRequestBase request, int code, string msg = null, LogLevel level = null)
 {
     if (string.IsNullOrEmpty(msg))
         log.Log(level ?? LogLevel.Warn, RequestInfo(string.Format("HTTP error code {0} for", code), request));
     else
         log.Log(level ?? LogLevel.Warn, RequestInfo(string.Format("HTTP error code {0} ({1}) for", code, msg), request));
 }
Beispiel #14
0
 public void Write(CommonLogger logType, LogLevel level, string message)
 {
     Logger logger = LoggerRepository.BuildLogger(logType);
     StringBuilder info = new StringBuilder();
     if (HttpContext.Current != null)
     {
         var urlReferrer = HttpContext.Current.Request.UrlReferrer;
         if (urlReferrer != null)
         {
             info.AppendLine("前一个请求地址:" + urlReferrer.ToString());
         }
         var behavior = HttpContext.Current.Request.Cookies["user"];
         if (behavior != null)
         {
             info.AppendLine("据用户跟踪,用户为:" + behavior);
         }
         info.AppendLine("MethodType:" + HttpContext.Current.Request.HttpMethod);
         info.AppendLine("ClientIP:" + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString());
         info.AppendLine("Browser:" + HttpContext.Current.Request.Browser.Type);
         if (HttpContext.Current.User.Identity.IsAuthenticated)
         {
             info.AppendLine("LoginUser:"******"请求地址:" + HttpContext.Current.Request.RawUrl);
     }
     DoWrite(logger, level, info.ToString() + message);
 }
Beispiel #15
0
        /// <summary>
        /// Log the input message in a specified level
        /// </summary>
        /// <param name="level">The desired logging level of the input message.</param>
        /// <param name="msg">The message to log.</param>
        public static void Log(LogLevel level, string msg)
        {
            // check if the internal logger is initialized
            if (logger == null)
            {
                return;
            }

            switch (level)
            {
                case LogLevel.Trace:
                    logger.Trace(msg);
                    break;
                case LogLevel.Debug:
                    logger.Debug(msg);
                    break;
                case LogLevel.Info:
                    logger.Info(msg);
                    break;
                case LogLevel.Warn:
                    logger.Warn(msg);
                    break;
                case LogLevel.Error:
                    logger.Error(msg);
                    break;
                case LogLevel.Fatal:
                    logger.Fatal(msg);
                    break;
            }
        }
Beispiel #16
0
        /// <summary>
        /// Logs a message at the specified log level with the specified object data and exception information
        /// </summary>
        /// <param name="level"></param>
        /// <param name="message"></param>
        /// <param name="data"></param>
        /// <param name="ex"></param>
        public void Log(NLog.LogLevel level, string message, object data = null, Exception ex = null)
        {
            var eventInfo = new LogEventInfo(level, "", message)
            {
                Exception = ex
            };

            if (data == null)
            {
                eventInfo.Properties["relatedData"] = null;
            }
            else
            {
                eventInfo.Properties["relatedData"] = JsonConvert.SerializeObject(data, (Newtonsoft.Json.Formatting)Formatting.None, JsonSettings);
            }
            if (_enableCorrealtionGuidLogging == true)
            {
                eventInfo.Properties["correlationId"] = CorrelationId;
            }
            else
            {
                eventInfo.Properties["correlationId"] = null;
            }
            eventInfo.Properties["applicationName"] = _applicationName;
            _logger.Log(eventInfo);
        }
Beispiel #17
0
 public void Log(LogLevel level, object value)
 {
     if (this.IsEnabled(level))
     {
         this.WriteToTargets(level, "{0}", new object[] { value });
     }
 }
Beispiel #18
0
 public void Log(LogLevel level, string message, object arg1, object arg2)
 {
     if (this.IsEnabled(level))
     {
         this.WriteToTargets(level, message, new[] { arg1, arg2 });
     }
 }
Beispiel #19
0
        public LogNode(XmlNode xmlNode,  ScriptableScraper context)
            : base(xmlNode, context)
        {
            try { logLevel = LogLevel.FromString(xmlNode.Attributes["LogLevel"].Value); }
            catch (Exception e) {
                if (e.GetType() == typeof(ThreadAbortException))
                    throw e;

                try { logLevel = LogLevel.FromString(xmlNode.Attributes["log_level"].Value); }
                catch (Exception e2) {
                    if (e2.GetType() == typeof(ThreadAbortException))
                        throw e2;

                    logLevel = LogLevel.Debug;
                }
            }

            try { message = xmlNode.Attributes["Message"].Value; }
            catch (Exception e) {
                if (e.GetType() == typeof(ThreadAbortException))
                    throw e;

                try { message = xmlNode.Attributes["message"].Value; }
                catch (Exception e2) {
                    if (e2.GetType() == typeof(ThreadAbortException))
                        throw e2;

                    logger.Error("Missing MESSAGE attribute on: " + xmlNode.OuterXml);
                    loadSuccess = false;
                    return;
                }
            }

            loadSuccess = true;
        }
        public static LoggingConfiguration UsePaperTrail(this LoggingConfiguration configuration, LogConfig config)
        {
            if (!string.IsNullOrEmpty(config.Papertrail?.Server))
            {
                var syslogTarget = new SyslogTarget
                {
                    Name            = "PaperTrail",
                    MessageCreation = new MessageBuilderConfig
                    {
                        Facility = Facility.Local7,
                        Rfc5424  = new Rfc5424Config
                        {
                            AppName  = config.ApplicationName,
                            Hostname = config.HostName ?? Environment.MachineName,
                        },
                    },
                    MessageSend = new MessageTransmitterConfig
                    {
                        Protocol = ProtocolType.Tcp,
                        Tcp      = new TcpConfig
                        {
                            Server = config.Papertrail.Server,
                            Port   = config.Papertrail.Port,
                            Tls    = new TlsConfig
                            {
                                Enabled = true,
                            },
                        },
                    },
                };

                configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(config.Papertrail.LogLevel ?? "Trace"), syslogTarget));
            }
            return(configuration);
        }
Beispiel #21
0
 public static void Log(string entry, LogLevel level = LogLevel.Info)
 {
     if (!_initialized) return;
     switch (level)
     {
         case LogLevel.Debug:
             _logger.Debug(entry);
             break;
         case LogLevel.Info:
             _logger.Info(entry);
             break;
         case LogLevel.Warning:
             _logger.Warn(entry);
             break;
         case LogLevel.Error:
             _logger.Error(entry);
             break;
         case LogLevel.Critical:
             _logger.Fatal(entry);
             break;
         default:
             _logger.Info(entry);
             break;
     }
 }
Beispiel #22
0
 private void SetOnlineLoggingLevel(NLog.LogLevel Level, bool Checked)
 {
     foreach (NLog.Config.LoggingRule rule in LogManager.Configuration.LoggingRules)
     {
         // Only update the appropriate rule
         // TODO don't just check the 0-index target!
         foreach (NLog.Targets.Target CurrentTarget in rule.Targets)
         {
             if (Level != NLog.LogLevel.Off)
             {
                 if (Checked)
                 {
                     rule.EnableLoggingForLevel(Level);
                 }
                 else
                 {
                     rule.DisableLoggingForLevel(Level);
                 }
             }
             else if (Checked)
             {
                 rule.DisableLoggingForLevel(NLog.LogLevel.Trace);
                 rule.DisableLoggingForLevel(NLog.LogLevel.Debug);
                 rule.DisableLoggingForLevel(NLog.LogLevel.Info);
                 rule.DisableLoggingForLevel(NLog.LogLevel.Warn);
                 rule.DisableLoggingForLevel(NLog.LogLevel.Error);
                 rule.DisableLoggingForLevel(NLog.LogLevel.Fatal);
             }
         }
     }
     LogManager.ReconfigExistingLoggers();
 }
Beispiel #23
0
        private LogEventInfo CreateLogEventInfo(NLog.LogLevel level, string message, IDictionary <string, object> dictionary, Exception exception)
        {
            LogEventInfo logEvent = new LogEventInfo(level, _logger.Name, message);

            foreach (var item in dictionary)
            {
                logEvent.Properties[item.Key] = item.Value;
            }

            if (exception != null)
            {
                logEvent.Properties["error-source"] = exception.Source;
                if (exception.TargetSite != null)
                {
                    if (exception.TargetSite.DeclaringType != null)
                    {
                        logEvent.Properties["error-class"] = exception.TargetSite.DeclaringType.FullName;
                    }
                    logEvent.Properties["error-method"] = exception.TargetSite.Name;
                }
                logEvent.Properties["error-message"] = exception.Message;

                if (exception.InnerException != null)
                {
                    logEvent.Properties["inner-error-message"] = exception.InnerException.Message;
                }
            }

            return(logEvent);
        }
        public static void Log(Logger logger, NLog.LogLevel LogLevel,
                               string Class, string Device, int seq_num, IMessage Data,
                               string VehicleID = null, string CarrierID = null, string LogID = null, string Level = null, string ThreadID = null, string Lot = null, string XID = null, string Transaction = null,
                               [CallerMemberName] string Method = "")
        {
            string function_name = $"[{seq_num}]{Data.Descriptor.Name}";

            LogConstants.Type?type = null;
            if (function_name.Contains("_"))
            {
                int      packet_id           = 0;
                string[] function_name_splil = function_name.Split('_');
                if (int.TryParse(function_name_splil[1], out packet_id))
                {
                    type = packet_id > 100 ? LogConstants.Type.Receive : LogConstants.Type.Send;
                }
            }
            Log(logger, LogLevel, Class, Device,
                Data: function_name,
                VehicleID: VehicleID,
                CarrierID: CarrierID,
                Type: type,
                LogID: LogID,
                Level: Level,
                ThreadID: ThreadID,
                Lot: Lot,
                XID: XID,
                Details: Data.ToString(),
                Method: Method
                );
        }
Beispiel #25
0
 protected override byte[] serializeMessage(LogLevel logLevel, string message)
 {
     var formattedMessage = formatLogMessage(logLevel.ToString(), message);
     var bytes = Encoding.UTF8.GetBytes(formattedMessage).ToList();
     bytes.Add(0);
     return bytes.ToArray();
 }
Beispiel #26
0
            public void Write(LogLevel level, LogEvent logEvent)
            {
                LogBuilder fluent;
                switch (level)
                {
                    case LogLevel.Trace:
                        fluent = _logger.Trace();
                        break;
                    case LogLevel.Info:
                        fluent = _logger.Info();
                        break;
                    case LogLevel.Warning:
                        fluent = _logger.Warn();
                        break;
                    case LogLevel.Error:
                        fluent = _logger.Error();
                        break;
                    case LogLevel.Critical:
                        fluent = _logger.Fatal();
                        break;
                    default:
                        throw new ApplicationException("Invalid log level");
                }

                if (!string.IsNullOrWhiteSpace(logEvent.Message))
                    fluent.Message(logEvent.Message);
                if (logEvent.Exception != null)
                    fluent.Exception(logEvent.Exception);
                foreach (var parameter in logEvent.Parameters)
                {
                    fluent.Property(parameter.Key, parameter.Value);
                }
                fluent.Write();
            }
Beispiel #27
0
        public void Log(LogLevel level, string message, params object[] arguments)
        {
            var info = new LogEventInfo(GetLevel(level), Key, message);
            info.Parameters = arguments;

            LogManager.GetLogger(Key).Log(info);
        }
        static public void SafeLog(string message, NLog.LogLevel logLevel)
        {
            if (Log != null && Log.Name != "Console")
            {
                int value = logLevel.Ordinal;
                switch (value)
                {
                case 0:
                    Log.Trace(message);
                    break;

                case 1:
                    Log.Debug(message);
                    break;

                case 2:
                    Log.Info(message);
                    break;

                case 3:
                    Log.Warn(message);
                    break;

                case 4:
                    Log.Error(message);
                    break;
                }
            }
        }
 private static void SetMemoryLevel(LogLevel minimumLevel)
 {
     SetTargetLevel(
         MemoryTargetName,
         minimumLevel,
         targetName => new MemoryTarget { Name = targetName });
 }
Beispiel #30
0
        /// <summary>
        /// Writes a log entry.
        /// </summary>
        /// <param name="logLevel">Entry will be written on this level.</param>
        /// <param name="eventId">Id of the event.</param>
        /// <param name="state">The entry to be written. Can be also an object.</param>
        /// <param name="exception">The exception related to this entry.</param>
        /// <param name="formatter">Function to create a string message of the state and exception.</param>
        public void Log <TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
        {
            string message = formatter(state, exception);

            NLog.LogLevel level = log.LogLevelMsToNlog(logLevel);
            log.LogAtLevel(level, "{0}", message);
        }
 public LogMessageModel(string message, LogLevel level, DateTime date)
 {
     _date = date;
     _message = message;
     _level = level;
     IsVisible = true;
 }
Beispiel #32
0
        /// <summary>
        /// Actually sends the message to the underlying log system.
        /// </summary>
        /// <param name="logLevel">the level of this log event.</param>
        /// <param name="message">the message to log</param>
        /// <param name="exception">the exception to log (may be null)</param>
        protected override void WriteInternal(LogLevel logLevel, object message, Exception exception)
        {
            LogLevelNLog level    = GetLevel(logLevel);
            LogEventInfo logEvent = new LogEventInfo(level, _logger.Name, null, "{0}", new object[] { message }, exception);

            _logger.Log(declaringType, logEvent);
        }
Beispiel #33
0
        public void SetLogLevel(string logLevel)
        {
            var level = LogLevel.FromString(logLevel);

            if (level == LogLevel.Off)
            {
                LogManager.DisableLogging();
            }
            else
            {
                if (!LogManager.IsLoggingEnabled())
                {
                    LogManager.EnableLogging();
                }
                foreach (var rule in LogManager.Configuration.LoggingRules)
                {
                    rule.DisableLoggingForLevels(LogLevel.Trace, LogLevel.Fatal);
                    // Iterate over all levels up to and including the target, (re)enabling them.
                    for (var i = level.Ordinal; i <= 5; i++)
                    {
                        rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
                    }
                }
            }

            LogManager.ReconfigExistingLoggers();
        }
Beispiel #34
0
        private void SendPayload(LogLevel level, string message, Exception exception)
        {
            if (exception == null)
            {
                return;
            }
            string exceptionType;
            var stackBuilder = new StringBuilder();

            do
            {
                exceptionType = exception.GetType().Name;
                stackBuilder.AppendLine(exception.Message);
                stackBuilder.AppendLine(exception.StackTrace);
                exception = exception.InnerException;
            } while (exception != null);

            manager.SendLoggingPayload(new LoggingPayload
            {
                StackTrace = stackBuilder.ToString(),
                Message = message,
                LogLevel = level.Name,
                ExceptionType = exceptionType
            });
        }
Beispiel #35
0
        /// <summary>
        /// Instantiate a Logger with the specified name and minimum message level
        /// </summary>
        /// <param name="name">Name of logger</param>
        /// <param name="minLevel">Messages of lower level than this will not be logged</param>
        /// <returns>Logger with appropriate name, minimum level and settings</returns>
        private Logger GetLogger(string name, NLog.LogLevel minLevel)
        {
            string savePath = GetSavePath();                                    //Generate save path

            var fileTarget    = new FileTarget();                               // Create a target
            var consoleTarget = new ConsoleTarget();

            if (String.IsNullOrWhiteSpace(name))
            {
                name = "Log";
            }

            _logConfig.AddTarget($"{name}_file", fileTarget);                   // Add the target to the configuration
            _logConfig.AddTarget($"{name}_console", consoleTarget);

            string time = _logStart.ToString("yyyyMMdd-HHmm");

            fileTarget.FileName = $@"{savePath}\{time}_{name}.log";             //set name (and path) of savefile
            fileTarget.Layout   = @"${date} | ${level} | ${message}";           //Define layout for file

            consoleTarget.Layout = @"${time} | ${level} | ${message}";

            var fileRule    = new LoggingRule(name, minLevel, fileTarget);      //Create logging rules...
            var consoleRule = new LoggingRule(name, minLevel, consoleTarget);

            _logConfig.LoggingRules.Add(fileRule);                              //...and add to configuration
            _logConfig.LoggingRules.Add(consoleRule);

            LogManager.Configuration = _logConfig;                              //Activate the configuration

            return(LogManager.GetLogger(name));
        }
Beispiel #36
0
            public void Log <TState>(Microsoft.Extensions.Logging.LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
            {
                NLog.LogLevel level   = Logger.GetNLogLevel(logLevel);
                string        message = formatter(state, exception);

                logger.Log(level, message);
            }
Beispiel #37
0
        private static LogLevel NLog2Method(NLog.LogLevel loglevel)
        {
            LogLevel level = LogLevel.Off;

            if (loglevel == NLog.LogLevel.Trace)
            {
                level = LogLevel.Trace;
            }
            else if (loglevel == NLog.LogLevel.Debug)
            {
                level = LogLevel.Debug;
            }
            else if (loglevel == NLog.LogLevel.Info)
            {
                level = LogLevel.Info;
            }
            else if (loglevel == NLog.LogLevel.Warn)
            {
                level = LogLevel.Warn;
            }
            else if (loglevel == NLog.LogLevel.Error)
            {
                level = LogLevel.Error;
            }
            else if (loglevel == NLog.LogLevel.Fatal)
            {
                level = LogLevel.Fatal;
            }
            return(level);
        }
 private static void SetChainsawLevel(LogLevel minimumLevel)
 {
     SetTargetLevel(
         ChainsawTargetName,
         minimumLevel,
         targetName => new ChainsawTarget { Name = targetName, Address = "udp://127.0.0.1:7071" });
 }
 public static void SetNLogTarget(Target target, LogLevel minLevel = null)
 {
     if (target != null)
     {
         SimpleConfigurator.ConfigureForTargetLogging(target, minLevel ?? LogLevel.Info);
     }
 }
Beispiel #40
0
        public static void Log(Logger logger, NLog.LogLevel LogLevel,
                               string Class, string Device, SXFY Data,
                               string VehicleID = null, string CST_ID_L = null, string CST_ID_R = null, string LogID = null, string Level = null, string ThreadID = null, string Lot = null, string XID = null, string Transaction = null,
                               [CallerMemberName] string Method = "")
        {
            return;

            //如果被F'Y',Y可以被2整除的話代表是收到的
            bool isReceive = Data.getF() % 2 == 0;

            LogConstants.Type type = isReceive ? LogConstants.Type.Receive : LogConstants.Type.Send;
            Log(logger, LogLevel, Class, Device,
                Data: $"[{Data.SystemByte}]{Data.StreamFunction}-{Data.StreamFunctionName}",
                VehicleID: VehicleID,
                CST_ID_L: CST_ID_L,
                CST_ID_R: CST_ID_R,
                Type: type,
                LogID: LogID,
                Level: Level,
                ThreadID: ThreadID,
                Lot: Lot,
                XID: XID,
                Details: Data.toSECSString(),
                Method: Method
                );
        }
Beispiel #41
0
    void testLogLevel(Action<string> logMethod, LogLevel logLvl, bool shouldLog)
    {
        var didLog = false;
        LogLevel eventLogLevel = LogLevel.Off;
        string eventMessage = null;
        Logger eventLogger = null;
        _logger.OnLog += (logger, logLevel, msg) => {
            didLog = true;
            eventLogger = logger;
            eventLogLevel = logLevel;
            eventMessage = msg;
        };

        logMethod(Message);

        didLog.should_be(shouldLog);

        if (shouldLog) {
            eventLogger.should_be_same(_logger);
            eventMessage.should_be(Message);
            eventLogLevel.should_be(logLvl);
        } else {
            eventMessage.should_be_null();
            eventLogLevel.should_be(LogLevel.Off);
            eventLogger.should_be_null();
        }
    }
        public static LoggingConfiguration UseElastic(this LoggingConfiguration configuration, LogConfig config)
        {
            if (!string.IsNullOrEmpty(config.Elastic?.Uri))
            {
                if (config.HostName.Contains("-"))
                {
                    throw new InvalidOperationException($"Dash character (-) is not allowed in the Logging.HostName property. Please check your application settings file.");
                }

                var target = new ElasticSearchTarget
                {
                    Name        = "Elastic",
                    CloudId     = config.Elastic.CloudId,
                    Username    = config.Elastic.Username,
                    Password    = config.Elastic.Password,
                    RequireAuth = true,
                    Uri         = config.Elastic.Uri,
                    Index       = $"logs-{config.HostName}",
                    Fields      = new List <Field>
                    {
                        new Field {
                            Name = "host.name", Layout = config.HostName
                        },
                        new Field {
                            Name = "application", Layout = config.ApplicationName
                        }
                    },
                    Layout = "${message}"
                };

                configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.FromString(config.Elastic.LogLevel ?? "Trace"), target));
            }

            return(configuration);
        }
Beispiel #43
0
 public void Log(string s, LogLevel level)
 {
     var box = level == LogLevel.Debug || level == LogLevel.Info || level == LogLevel.Trace ? infoBox : logBox;
     while (box.Items.Count > 8)
         box.Items.RemoveAt(0);
     box.Items.Add(s);
 }
Beispiel #44
0
 public void Log(LogLevel level, IFormatProvider formatProvider, object value) 
 {
     if (this.IsEnabled(level))
     {
         this.WriteToTargets(level, formatProvider, "{0}", new[] { value });
     }
 }
Beispiel #45
0
        public static LogLevel TranslateLogLevel(NLogLevel level)
        {
            // The levels are in the order of usage
            var name = level?.Name;

            switch (name)
            {
            case "Info":
                return(LogLevel.Info);

            case "Debug":
                return(LogLevel.Debug);

            case "Warn":
                return(LogLevel.Warn);

            case "Error":
                return(LogLevel.Error);

            case "Trace":
                return(LogLevel.Trace);

            case "Fatal":
                return(LogLevel.Fatal);

            default:
                return(LogLevel.None);
            }
        }
Beispiel #46
0
 void send(Logger logger, LogLevel logLevel, string message)
 {
     message = _defaultFormatter.FormatMessage(logger, logLevel, message);
     message = _timestampFormatter.FormatMessage(logger, logLevel, message);
     message = _colorFormatter.FormatMessage(logLevel, message);
     _socket.Send(logLevel, message);
 }
Beispiel #47
0
		private DebugTarget GetDebugTarget(LogLevel level)
		{
			DebugTarget debugTarget = new DebugTarget();
			debugTarget.Layout = "${message}";
			SimpleConfigurator.ConfigureForTargetLogging(debugTarget, level);
			return debugTarget;
		}
 public static void Log(string loggerName, LogLevel logLevel, string eventID, string message)
 {
     LogEventInfo logEvent = new LogEventInfo(logLevel, _logger.Name, message);
     logEvent.Properties["EventID"] = eventID;
     logEvent.Properties["LoggerName"] = loggerName;
     _logger.Log(typeof(EventLogger), logEvent);
 }
Beispiel #49
0
        /// <summary>
        /// Convert the Log Level from the internal MPTagThat Loglevel to NLog
        /// </summary>
        /// <param name="level"></param>
        /// <returns></returns>
        private NLog.LogLevel ConvertLogLevel(LogLevel level)
        {
            NLog.LogLevel nlogLogLevel = NLog.LogLevel.Debug;

            switch (level)
            {
            case LogLevel.Debug:
                nlogLogLevel = NLog.LogLevel.Debug;
                break;

            case LogLevel.Error:
                nlogLogLevel = NLog.LogLevel.Error;
                break;

            case LogLevel.Info:
                nlogLogLevel = NLog.LogLevel.Info;
                break;

            case LogLevel.Warn:
                nlogLogLevel = NLog.LogLevel.Warn;
                break;

            case LogLevel.Trace:
                nlogLogLevel = NLog.LogLevel.Trace;
                break;
            }

            return(nlogLogLevel);
        }
        private static void LogProgressMessage(Logger logger, LogLevel level, string message)
        {
            var logEvent = new LogEventInfo(level, logger.Name, message);
            logEvent.Properties.Add("Status", "");

            logger.Log(logEvent);
        }
Beispiel #51
0
            /// <summary>
            /// Записывает в журнал сообщение
            /// </summary>
            /// <param name="type">Тип журнала</param>
            /// <param name="level">Уровень сообщения</param>
            /// <param name="message">Сообщение</param>
            /// <param name="parameters">Параметры формирования сообщения</param>
            private static void Log(LogType type, NLog.LogLevel level, string message, params object[] parameters)
            {
                try
                {
                    NLog.Logger logger = GetLogger(type);
                    if (logger == null)
                    {
                        return;
                    }

                    if (logger.IsEnabled(level))
                    {
                        string msg = parameters.Length > 0 ? string.Format(message, parameters) : message;
                        logger.Log(level, msg);
                    }
                }
                catch (Exception le)
                {
                    if (type != LogType.System)
                    {
                        Logger.LogException(LogType.System, LogLevel.Error, le, "Ошибка при записи в журнал {0}", type);
                    }

                    throw;
                }
            }
Beispiel #52
0
        public static void SetupLogging(LogLevel logLevel)
        {
            // Step 1. Create configuration object 
            var config = new LoggingConfiguration();

            // Step 2. Create targets and add them to the configuration 
            var debuggerTarget = new DebuggerTarget();
            config.AddTarget("debugger", debuggerTarget);

            var fileTarget = new FileTarget();
            config.AddTarget("file", fileTarget);

            // Step 3. Set target properties 
            debuggerTarget.Layout = @"${logger:shortName=True} - ${uppercase:${level}}: ${message}";
            fileTarget.FileName = "${specialfolder:folder=MyDocuments}/Artemis/logs/${shortdate}.txt";
            fileTarget.Layout = "${longdate}|${level:uppercase=true}|${logger}|${message} ${exception:format=tostring}";
            fileTarget.EnableFileDelete = true;
            fileTarget.MaxArchiveFiles = 7;
            fileTarget.ArchiveEvery = FileArchivePeriod.Minute;
            
            // Step 4. Define rules
            var rule1 = new LoggingRule("*", logLevel, debuggerTarget);
            config.LoggingRules.Add(rule1);
            var rule2 = new LoggingRule("*", logLevel, fileTarget);
            config.LoggingRules.Add(rule2);

            // Step 5. Activate the configuration
            LogManager.Configuration = config;

            // Log as fatal so it always shows
            var logger = LogManager.GetCurrentClassLogger();
            logger.Fatal("INFO: Set log level to {0}", logLevel);
        }
 public LogMessageModel(string message, LogLevel level, DateTime date)
 {
     this.Date = date;
     this.message = message;
     this.level = level;
     IsVisible = true;
 }
Beispiel #54
0
        private static void SetupLogging(string filename, LogLevel level, string path, string archivePath)
        {
            try
            {
                LoggingConfiguration config = new LoggingConfiguration();

                // Configuration for application
                FileTarget fileTarget = new FileTarget();
                fileTarget.FileName = path + @"\" + filename;
                fileTarget.Layout = LogConstants.LOG_FORMAT;
                fileTarget.Encoding = Encoding.UTF8;
                fileTarget.ArchiveFileName = archivePath + LogConstants.ARCHIVE_FILE_NAME + new DirectoryInfo(filename).Name;
                fileTarget.ArchiveEvery = FileArchivePeriod.Day;
                fileTarget.ArchiveNumbering = ArchiveNumberingMode.Date;
                fileTarget.ArchiveDateFormat = LogConstants.ARCHIVE_DATE_FORMAT;
                fileTarget.ArchiveAboveSize = LogConstants.MAX_LOG_FILE_SIZE;
                fileTarget.MaxArchiveFiles = LogConstants.MAX_NUM_ARCHIVE_FILE;
                fileTarget.ConcurrentWrites = true;
                fileTarget.ConcurrentWriteAttempts = 5;
                fileTarget.ConcurrentWriteAttemptDelay = 5;
                fileTarget.CreateDirs = true;
                fileTarget.EnableFileDelete = true;
                fileTarget.DeleteOldFileOnStartup = true;
                config.AddTarget("file", fileTarget);

                // Configuration for ravendb
                FileTarget fileTargetRaven = new FileTarget();
                fileTargetRaven.FileName = path + Path.GetDirectoryName(filename) + @"\" + "raven_" + new DirectoryInfo(filename).Name;
                fileTargetRaven.Layout = LogConstants.LOG_FORMAT;
                fileTargetRaven.ArchiveFileName = archivePath + LogConstants.ARCHIVE_FILE_NAME + "raven_" + new DirectoryInfo(filename).Name;
                fileTargetRaven.ArchiveEvery = FileArchivePeriod.Day;
                fileTargetRaven.ArchiveNumbering = ArchiveNumberingMode.Date;
                fileTargetRaven.ArchiveDateFormat = LogConstants.ARCHIVE_DATE_FORMAT;
                fileTargetRaven.ArchiveAboveSize = LogConstants.MAX_LOG_FILE_SIZE;
                fileTargetRaven.MaxArchiveFiles = LogConstants.MAX_NUM_ARCHIVE_FILE;
                fileTargetRaven.ConcurrentWrites = true;
                fileTargetRaven.ConcurrentWriteAttempts = 5;
                fileTargetRaven.ConcurrentWriteAttemptDelay = 5;
                fileTargetRaven.CreateDirs = true;
                fileTargetRaven.EnableFileDelete = true;
                fileTargetRaven.DeleteOldFileOnStartup = true;
                config.AddTarget("fileRaven", fileTargetRaven);

                // Logging rule for ravendb
                LoggingRule ruleRaven = new LoggingRule("Raven.*", NLogLevel(LogLevel.Error), fileTargetRaven);
                ruleRaven.Final = true;

                // Logging rule for application
                LoggingRule rule = new LoggingRule("*", NLogLevel(level), fileTarget);
                config.LoggingRules.Add(ruleRaven);
                config.LoggingRules.Add(rule);

                LogManager.Configuration = config;
            }
            catch (Exception x)
            {
                throw x;
            }
        }
Beispiel #55
0
 public void Send(LogLevel logLevel, string message)
 {
     if (isSocketReady()) {
         socket.Send(serializeMessage(logLevel, message));
     } else {
         _history.Add(new HistoryItem(logLevel, message));
     }
 }
Beispiel #56
0
 private LogEventInfo CreateLogEventInfo(NLog.LogLevel nLogLogLevel, string message, IReadOnlyList <KeyValuePair <string, object> > parameterList)
 {
     if (parameterList != null && parameterList.Count > 0 && IsNonDigitValue(parameterList[0].Key))
     {
         return(CreateLogEventInfoWithMultipleParameters(nLogLogLevel, message, parameterList));
     }
     return(LogEventInfo.Create(nLogLogLevel, _logger.Name, message));
 }
Beispiel #57
0
        private void enabledToolStripMenuItem_CheckStateChanged(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;

            NLog.LogLevel selectedLevel = (NLog.LogLevel)item.Tag;
            SetOnlineLoggingLevel(selectedLevel, item.Checked);
            UpdateOnlineLoggingLevel();
        }
Beispiel #58
0
 static void LogEvent(NLogger logger,
                      NLogLevel level,
                      string logSource,
                      string message,
                      params object[] parameters)
 {
     LogEvent(logger, level, logSource, null, message, parameters);
 }
Beispiel #59
0
 /// <summary>
 /// Add a message to the log.
 ///</summary>
 private void Log(LogLevel level, string message)
 {
     if (Application.Current != null)
     {
         Application.Current.Dispatcher.InvokeAsync(() =>
                                                    _logger.Log(level, message));
     }
 }
Beispiel #60
0
    private static void ChangeLogLevel(NLog.LogLevel minLevel)
    {
        _logger.Debug("Log level changed: {0}", minLevel);

        var rootLoggingRule = NLog.LogManager.Configuration.LoggingRules.First(n => n.NameMatches("*"));

        rootLoggingRule.EnableLoggingForLevels(minLevel, NLog.LogLevel.Fatal);
        NLog.LogManager.ReconfigExistingLoggers();
    }