Ejemplo n.º 1
0
            public static void WriteLog(string messageFormat, LoggingLevel loggingLevel = LoggingLevel.Default, params object[] args) {
                //WriteLog(String.Format(message, args), loggingLevel);
#if DEBUG
                lock (lockFlag) {
#endif
                    {
                        string message = messageFormat;
                        bool isNotMessageFormatted = true;

                        try {
                            message = string.Format(messageFormat, args);
                            isNotMessageFormatted = false;
                        }
                        catch { }

                        WriteConsole(message);

                        if (IsLoggingToFileEnabled) {
                            if (message.Length < 20 * 1024) {
                                LogToFile(message);
                            }
                        }
                    }
#if DEBUG
                }
#endif
            }
 public void LogException(MethodBase methodBase, Exception err, LoggingLevel exceptionLevel)
 {
     ILog logger = LogManager.GetLogger(methodBase.DeclaringType);
     if (ShouldLog(logger, exceptionLevel, methodBase)) {
         exceptionLogger.LogException(err, false, methodBase.DeclaringType);
     }
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Log a message
 /// </summary>
 /// <param name="level"></param>
 /// <param name="function"></param>
 /// <param name="message"></param>
 /// <param name="ex"></param>
 public static void Log(LoggingLevel level, string function, string message, Exception ex)
 {
     if (level >= minLevel)
     {
         // log message to file, email, pager
     }
 }
        /// <summary>
        /// Parses the XML of the configuration section.
        /// </summary>
        /// <param name="parent">The configuration settings in a corresponding parent configuration section.</param>
        /// <param name="configContext">An HttpConfigurationContext when Create is called from the ASP.NET configuration system. Otherwise, this parameter is reserved and is a null reference.</param>
        /// <param name="section">The XmlNode that contains the configuration information from the configuration file. Provides direct access to the XML contents of the configuration section.</param>
        /// <returns>A configuration object.</returns>
        public object Create(object parent, object configContext, XmlNode section)
        {
            XmlElement loggingElement = (XmlElement) section;
            if (loggingElement.HasAttribute("LoggingLevel"))
            {
                loggingLevel = (LoggingLevel) Enum.Parse(typeof(LoggingLevel), loggingElement.GetAttribute("LoggingLevel"), true);
            }
            else
            {
                loggingLevel = LoggingLevel.Off;
            }

            if (loggingElement.HasChildNodes)
            {
                foreach (XmlElement element in loggingElement.SelectNodes("logger"))
                {
                    string typeName = element.GetAttribute("type");

                    // Use reflection to create an instance of the configured Logger instance
                    Type type = Type.GetType(typeName);
                    LoggerBase logger = (LoggerBase) type.Assembly.CreateInstance(type.FullName);
                    logger.Configure(element);
                    loggers.Add(logger);
                }
            }

            return this;
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Initializes a new LogItem class
 /// </summary>
 /// <param name="message">Message to log</param>
 /// <param name="exception">Exception to log</param>
 /// <param name="level">Message level</param>
 public LogItem(string message, Exception exception = null, LoggingLevel level = LoggingLevel.Info)
 {
     Message = message;
     Exception = exception;
     Created = DateTime.UtcNow;
     Level = level;
 }
 public void Log(Exception exception, LoggingLevel loggingLevel, [CallerMemberName] string memberName = "", [CallerFilePath] string classFilePath = "", [CallerLineNumber]int line = 0)
 {
     if (exception != null)
     {
         Log(exception.Message, loggingLevel, memberName, classFilePath, line);
     }
 }
Ejemplo n.º 7
0
        protected override void Log(LoggingLevel level, object sender, object message, object verbose, Exception t)
        {
            if (!(IsVerboseEnabled))
                verbose = "";

            WriteLine(level, message.ToString() + "; " + t.ToString() + "; " + verbose, sender); // do not localize
        }
 /// <summary>
 /// Initializes a new instance of the 
 /// <see cref="T:WebApplications.Utilities.Logging.LoggingException" /> class.
 /// </summary>
 /// <param name="level">The log level.</param>
 /// <param name="resource">The resource expression, e.g. ()=&gt; Resources.Log_Message.</param>
 /// <param name="parameters">The parameters.</param>
 internal CommonServiceException(
     LoggingLevel level,
     [CanBeNull] Expression<Func<string>> resource,
     [CanBeNull] params object[] parameters)
     : base(level, resource, parameters)
 {
 }
Ejemplo n.º 9
0
        public override void LogEntry(string source, string message, LoggingLevel loggingLevel)
        {
            if (EventLog.Exists(logName))
            {
                StringWriter writer = new StringWriter();
                writer.WriteLine("Source: " + source);
                writer.WriteLine("Message: " + message);
                message = writer.ToString();

                switch (loggingLevel)
                {
                    case LoggingLevel.Error:
                        EventLog.WriteEntry(logName, message, EventLogEntryType.Error);
                        break;
                    case LoggingLevel.Warning:
                        EventLog.WriteEntry(logName, message, EventLogEntryType.Warning);
                        break;
                    case LoggingLevel.Information:
                    case LoggingLevel.Verbose:
                        EventLog.WriteEntry(logName, message, EventLogEntryType.Information);
                        break;
                    default:
                        break;
                }
            }
            else
            {
                StringWriter writer = new StringWriter();
                writer.WriteLine("Entries cannot be written to the " + logName + " log because it does not exist.");
                writer.WriteLine("Source: " + source);
                writer.WriteLine("Message: " + message);

                throw new InvalidOperationException(writer.ToString());
            }
        }
Ejemplo n.º 10
0
 public Logger(string path, LoggingLevel level, params TextWriter[] otherOutputs)
 {
     _path = path;
     _level = level;
     _otherOutputs = otherOutputs;
     _messageBuffer = new List<string>();
 }
Ejemplo n.º 11
0
        private static void LogMessage(object sender, LoggingLevel loggingLevel, string message, params object[] args)
        {
            try
            {
                string loggerName = "Main";
                if (sender != null)
                {
                    loggerName = sender.GetType().Name;
                }

                message = string.Format(message, args);

                Logger logger = LogManager.GetLogger(loggerName);
                switch (loggingLevel)
                {
                    case LoggingLevel.Error: logger.Error(message); break;
                    case LoggingLevel.Warning: logger.Warn(message); break;
                    case LoggingLevel.Info: logger.Info(message); break;
                    case LoggingLevel.Critical: logger.Fatal(message); break;
                    default: logger.Debug(message); break;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("NLog exception: {0}, {1}", ex.Message, ex.StackTrace));
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="LoggingException" /> class.
 /// </summary>
 /// <param name="level">The severity of the exception being logged.</param>
 /// <param name="resource">The resource expression, e.g. ()=&gt; Resources.Log_Message.</param>
 /// <param name="parameters">The parameters.</param>
 public DatabaseSchemaException(
     LoggingLevel level,
     [CanBeNull] Expression<Func<string>> resource,
     [CanBeNull] params object[] parameters)
     : base(level, resource, parameters)
 {
 }
Ejemplo n.º 13
0
 public static void Log(LoggingLevel level, Exception exception)
 {
     if (exception != null)
     {
         Log(level, exception.ToString());
     }
 }
Ejemplo n.º 14
0
        public static void Log(LoggingLevel level, string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            string path = LogPath;

            if (level == LoggingLevel.WxPay)
            {
                path = WxPayLogPath;
            }

            if (!Directory.Exists(path))//如果日志目录不存在就创建
            {
                Directory.CreateDirectory(path);
            }

            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//获取当前系统时间
            string filename = path + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//用日期对日志文件命名

            //创建或打开日志文件,向日志文件末尾追加记录
            StreamWriter mySw = File.AppendText(filename);

            //向日志文件写入内容
            string write_content = time + "\r\n" + message;
            mySw.WriteLine(write_content);

            //关闭日志文件
            mySw.Close();
        }
        public void LogEntry(MethodBase methodBase, object[] argumentValues, LoggingLevel entryLevel)
        {
            var logger = LogManager.GetLogger(methodBase.DeclaringType);
            if (this.ShouldLog(logger, entryLevel, methodBase))
            {
                var logMessage = new StringBuilder();
                logMessage.Append(string.Format("{0}(", methodBase.Name));

                var parameterInfos = methodBase.GetParameters();
                if (argumentValues != null && parameterInfos != null)
                {
                    for (var i = 0; i < argumentValues.Length; i++)
                    {
                        if (i > 0)
                        {
                            logMessage.Append(" ");
                        }

                        logMessage.Append(string.Format("{0}:[{1}]", parameterInfos[i].Name, argumentValues[i]));
                    }
                }

                logMessage.Append(")");
                logger.Log(entryLevel, logMessage.ToString());
            }
        }
Ejemplo n.º 16
0
 public static void WriteLine(string message, LoggingLevel level)
 {
     if (Level >= level)
       {
     if (LogEntryAdded != null)
       LogEntryAdded(null, new LogEventArgs(message));
       }
 }
Ejemplo n.º 17
0
 protected override void Log(LoggingLevel level, object sender, object message, object verbose)
 {
     if (!(IsVerboseEnabled))
         verbose = "";
     WriteLine(level,
               DateTime.Now.ToString("yyyy-dd-MM HH:mm:ss") + "; " + level.ToString() + "; " +
               sender.GetType().ToString() + "; " + message.ToString() + "; " + verbose); // do not localize
 }
        private bool ShouldLog(ILog logger, LoggingLevel loggingLevel, MethodBase methodBase)
        {
            if (methodBase != null && methodBase.Name != null) {
                return logger.IsEnabledFor(loggingLevel);
            }

            return false;
        }
Ejemplo n.º 19
0
        public Logger(string path, LoggingLevel level, params TextWriter[] otherOutputs)
        {
            _path = path;
            _level = level;
            _otherOutputs = otherOutputs;

            InitializeFile(_path, true);
        }
Ejemplo n.º 20
0
 public Logger(string path, LoggingLevel level, params TextWriter[] otherOutputs)
 {
     _path = path;
     _level = level;
     _otherOutputs = otherOutputs;
     _messageBuffer = new List<string>();
     _extraWhiteSpace = new Regex(@"\s\s+");
 }
 public void LogSuccess(MethodBase methodBase, object returnValue, LoggingLevel successLevel)
 {
     ILog logger = LogManager.GetLogger(methodBase.DeclaringType);
     if (ShouldLog(logger, successLevel, methodBase)) {
         logger.Log(LoggingLevel.Debug,
                    string.Format("{0} Returns:[{1}]", methodBase.Name,
                                  returnValue != null ? returnValue.ToString() : ""));
     }
 }
Ejemplo n.º 22
0
 private static void LogException(object sender, LoggingLevel loggingLevel, Exception ex)
 {
     Exception exceptionToLog = ex;
     while (ex.InnerException != null)
     {
         ex = ex.InnerException;
     }
     LogMessage(sender, loggingLevel, string.Format("Exception thrown - {0}.{1} Stacktrace - {2}", ex.Message, Environment.NewLine, ex.StackTrace));
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Trägt eine Meldung ins Ereignisprotokoll ein, wenn die Schwere der Meldung
        /// gemäß der Konfiguration des VCR.NET Recording Service eine Protokollierung
        /// gestattet.
        /// </summary>
        /// <param name="level">Schwere der Meldung.<seealso cref="ShouldLog"/></param>
        /// <param name="entryType">Art des Eintrags ins Ereignisprotokoll.</param>
        /// <param name="format">Format für den Aufbau der Meldung.</param>
        /// <param name="args">Parameter für den Aufbau der Meldung.</param>
        public static void Log( LoggingLevel level, EventLogEntryType entryType, string format, params object[] args )
        {
            // Nothing more to do
            if (!ShouldLog( level ))
                return;

            // Report
            EventLog.WriteEntry( string.Format( format, args ), entryType );
        }
Ejemplo n.º 24
0
 public LoggerBase(LoggingLevel level, bool isVerboseEnabled)
 {
     this.isVerboseEnabled = isVerboseEnabled;
     switch (level)
     {
         case LoggingLevel.All:
             isDebugEnabled = true;
             isInfoEnabled = true;
             isWarnEnabled = true;
             isErrorEnabled = true;
             isFatalEnabled = true;
             break;
         case LoggingLevel.Debug:
             isDebugEnabled = true;
             isInfoEnabled = true;
             isWarnEnabled = true;
             isErrorEnabled = true;
             isFatalEnabled = true;
             break;
         case LoggingLevel.Info:
             isDebugEnabled = false;
             isInfoEnabled = true;
             isWarnEnabled = true;
             isErrorEnabled = true;
             isFatalEnabled = true;
             break;
         case LoggingLevel.Warn:
             isDebugEnabled = false;
             isInfoEnabled = false;
             isWarnEnabled = true;
             isErrorEnabled = true;
             isFatalEnabled = true;
             break;
         case LoggingLevel.Error:
             isDebugEnabled = false;
             isInfoEnabled = false;
             isWarnEnabled = false;
             isErrorEnabled = true;
             isFatalEnabled = true;
             break;
         case LoggingLevel.Fatal:
             isDebugEnabled = false;
             isInfoEnabled = false;
             isWarnEnabled = false;
             isErrorEnabled = false;
             isFatalEnabled = true;
             break;
         case LoggingLevel.Off:
             isDebugEnabled = false;
             isInfoEnabled = false;
             isWarnEnabled = false;
             isErrorEnabled = false;
             isFatalEnabled = false;
             break;
     }
 }
Ejemplo n.º 25
0
        public override void LogEntry(string source, string message, LoggingLevel loggingLevel)
        {
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@Source", source),
                new SqlParameter("@Message", message),
                new SqlParameter("@LoggingLevel", loggingLevel)
            };

            SqlClientUtility.ExecuteNonQuery(connectionStringName, CommandType.StoredProcedure, commandText, parameters);
        }
Ejemplo n.º 26
0
        public static void ReconfigureLogLevel(LoggingLevel level)
        {
            foreach (var rule in LogManager.Configuration.LoggingRules)
            {
                // Remove all levels
                rule.DisableLoggingForLevel(LogLevel.Trace);
                rule.DisableLoggingForLevel(LogLevel.Info);
                rule.DisableLoggingForLevel(LogLevel.Debug);
                rule.DisableLoggingForLevel(LogLevel.Warn);
                rule.DisableLoggingForLevel(LogLevel.Error);
                rule.DisableLoggingForLevel(LogLevel.Fatal);

                switch (level)
                {
                    case LoggingLevel.Trace:
                        rule.EnableLoggingForLevel(LogLevel.Trace);
                        rule.EnableLoggingForLevel(LogLevel.Info);
                        rule.EnableLoggingForLevel(LogLevel.Debug);
                        rule.EnableLoggingForLevel(LogLevel.Warn);
                        rule.EnableLoggingForLevel(LogLevel.Error);
                        rule.EnableLoggingForLevel(LogLevel.Fatal);
                        break;
                    case LoggingLevel.Info:
                        rule.EnableLoggingForLevel(LogLevel.Info);
                        rule.EnableLoggingForLevel(LogLevel.Debug);
                        rule.EnableLoggingForLevel(LogLevel.Warn);
                        rule.EnableLoggingForLevel(LogLevel.Error);
                        rule.EnableLoggingForLevel(LogLevel.Fatal);
                        break;
                    case LoggingLevel.Debug:
                        rule.EnableLoggingForLevel(LogLevel.Debug);
                        rule.EnableLoggingForLevel(LogLevel.Warn);
                        rule.EnableLoggingForLevel(LogLevel.Error);
                        rule.EnableLoggingForLevel(LogLevel.Fatal);
                        break;
                    case LoggingLevel.Warn:
                        rule.EnableLoggingForLevel(LogLevel.Warn);
                        rule.EnableLoggingForLevel(LogLevel.Error);
                        rule.EnableLoggingForLevel(LogLevel.Fatal);
                        break;
                    case LoggingLevel.Error:
                        rule.EnableLoggingForLevel(LogLevel.Error);
                        rule.EnableLoggingForLevel(LogLevel.Fatal);
                        break;
                    case LoggingLevel.Fatal:
                        rule.EnableLoggingForLevel(LogLevel.Fatal);
                        break;
                }
            }

            //Call to update existing Loggers created with GetLogger() or
            //GetCurrentClassLogger()
            LogManager.ReconfigExistingLoggers();
        }
Ejemplo n.º 27
0
 public static void WriteLine(LoggingLevel level, string format, params object[] args)
 {
     string message = string.Format(format, args);
     if (UseStackFrame)
     {
         string name = new StackFrame(2).GetMethod().Name;
         message = string.Format(string.Format("[{0} - {1}] ", level, name) + format, args);
     }
     Debug.WriteLine(message);
     WriteToFile(message);
 }
        public void WriteEntry(string entry, LoggingLevel level = LoggingLevel.Error, int updateId = -1)
        {
            if (Level <= level)
            {
                if(updateId > 0)//to drop each update in a single file
                    File.AppendAllLines(_fileName + updateId, new List<string> { $"{DateTime.Now.ToString("s")}|{level.ToString().ToUpper()}|{entry}" });
                else
                    File.AppendAllLines(_fileName, new List<string> { $"{DateTime.Now.ToString("s")}|{level.ToString().ToUpper()}|{entry}" });

                Console.WriteLine($"{DateTime.Now.ToString("s")}|{level.ToString().ToUpper()}|{entry}");
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Writes the args to the default logging output using the format provided.
        /// </summary>
        public static void WriteLine(LoggingLevel level,string format, params object[] args)
        {
            var name = new StackFrame(2,false).GetMethod().Name;

            string prefix = string.Format("[{0} - {1}] ",level,name);
            string message = string.Format(prefix + format, args);

            Console.WriteLine(message);

            //if (level != LoggingLevel.Info)
                WriteToFile(message);
        }
Ejemplo n.º 30
0
        public override void LogEntry(string source, string message, LoggingLevel loggingLevel)
        {
            string entry = format;
            entry = entry.Replace("%source", source);
            entry = entry.Replace("%message", message);
            entry = entry.Replace("%loggingLevel", loggingLevel.ToString());
            entry = entry.Replace("%datetime", DateTime.Now.ToString());
            entry = entry.Replace("%newline", Environment.NewLine);
            entry = entry.Replace("%tab", "\t");

            Trace.Write(entry);
        }
Ejemplo n.º 31
0
        // Token: 0x0600004F RID: 79 RVA: 0x0000265C File Offset: 0x0000085C
        protected virtual void Log(LoggingLevel loggingLevel, string format, params object[] arguments)
        {
            if (!this.config.IsLoggingEnabled)
            {
                return;
            }
            if (this.config.LoggingLevel < loggingLevel)
            {
                return;
            }
            IList <object> list = new List <object>(DiagnosticLogger.Columns.Length);
            string         item = (arguments.Length != 0) ? new StringBuilder(format.Length).AppendFormat(format, arguments).ToString() : format;

            list.Add(DateTime.UtcNow);
            list.Add(loggingLevel);
            list.Add(item);
            this.log.Append(list);
        }
Ejemplo n.º 32
0
 private static void WriteLine(string msg, LoggingLevel level)
 {
     if (_logLevel >= level && EnableTimeStamp)
     {
         try
         {
             System.Diagnostics.Trace.WriteLine(string.Format("{0} " + msg, System.DateTime.Now));
         }
         catch (Exception)
         {
             System.Diagnostics.Trace.WriteLine("The tracing of the folloging message throw an error: " + msg);
         }
     }
     else if (_logLevel >= level)
     {
         System.Diagnostics.Trace.WriteLine(msg);
     }
 }
Ejemplo n.º 33
0
 public void Log(string message, Exception exception, LoggingLevel level)
 {
     if (_queue.Count > MAX_QUEUE_RECORD_LIMIT)
     {
         if (!QueueIsOverloadedWarning)
         {
             QueueIsOverloadedWarning = true;
             _queue.Enqueue(new LogItem(String.Format("MAX QUEUE COUNT WAS EXCEEDED (CURRENT: {0})! ADDING NEW MSG INTO QUEUE IS STOPPED!\r\n", _queue.Count), null, LoggingLevel.Fatal));
         }
         return;
     }
     if (QueueIsOverloadedWarning)
     {
         QueueIsOverloadedWarning = false;
         _queue.Enqueue(new LogItem("MAX QUEUE COUNT IS NORMALIZED! CONTINUE TO ADD NEW MSG INTO QUEUE!\r\n", null, LoggingLevel.Fatal));
     }
     _queue.Enqueue(new LogItem(message, exception, level));
 }
Ejemplo n.º 34
0
        public void Log(string info, LoggingLevel level)
        {
            var mth        = new StackTrace().GetFrame(2).GetMethod();
            var cls        = mth?.ReflectedType?.Name ?? "unknown name";
            var methodName = mth.Name;

            lock (_itemsLock)
            {
                this.Logs.Add(new LogEntryModel()
                {
                    Level       = level,
                    Time        = DateTime.Now,
                    Information = info,
                    Source      = cls,
                    MethodName  = methodName
                });
            }
        }
Ejemplo n.º 35
0
        public static void RegisterLogger(ISyncEngineLogger logger, LoggingLevel maxLoggingLevel, int daysOfServiceHistoryToMaintain)
        {
            if (logger == null)
            {
                throw new Exception("Logger can not be null.");
            }

            var loggingLevel = maxLoggingLevel == LoggingLevel.InheritFromParent ? ServiceLoggingLevel : maxLoggingLevel;

            var loggerToRegister = new RegisteredLogger(logger, loggingLevel, daysOfServiceHistoryToMaintain);

            if (!registeredLoggers.Contains(loggerToRegister))
            {
                registeredLoggers.Add(loggerToRegister);
            }

            DeleteExpiredLoggerHistory(loggerToRegister);
        }
Ejemplo n.º 36
0
        protected override string Format(LoggingLevel level, string message, Exception exception)
        {
            if (level.IsSeriousError())
            {
                lock (myMonitor)
                {
                    myExceptions.Add(exception ?? new Exception(message));
                }
            }

            return(JetBrains.Diagnostics.Log.DefaultFormat(
                       DateTime.Now,
                       level,
                       Category,
                       Thread.CurrentThread,
                       message,
                       exception));
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Queues a message to be sent to the endpoint
        /// </summary>
        /// <param name="toLog">The message to log</param>
        /// <param name="levelToLog">If the log level is higher (less frequent) than the application has set, it will cause the log to flush</param>
        public static void Log(string toLog, LoggingLevel levelToLog = LoggingLevel.Call)
        {
            if (!IsListening)
            {
                return;
            }

            lock (ObjectLock)
            {
                Queue.Append(toLog);
                Queue.Append(System.Environment.NewLine);
            }

            if (levelToLog >= Level)
            {
                Flush();
            }
        }
Ejemplo n.º 38
0
        private static void LogBase(LoggingLevel pLoggingLevel, String pMessage, Object pLoggingProperties, Exception pException)
        {
            if (_isInitialized && ShouldLog(_logger, pLoggingLevel))
            {
                switch (pLoggingLevel)
                {
                case LoggingLevel.Debug: _logger.Debug(pMessage, pException); break;

                case LoggingLevel.Info: _logger.Info(pMessage, pException); break;

                case LoggingLevel.Warning: _logger.Warn(pMessage, pException); break;

                case LoggingLevel.Error: _logger.Error(pMessage, pException); break;

                case LoggingLevel.Fatal: _logger.Fatal(pMessage, pException); break;
                }
            }
        }
Ejemplo n.º 39
0
        private async Task AddLogLine(string logLine, LoggingLevel level)
        {
            Debug.WriteLine(logLine);
            logBlock.Add(logLine);
            if (logBlock.Count >= LOG_BLOCK_MAX)
            {
                await WriteLogBlock();
            }

            if (level >= recentLevel)
            {
                recentLogs.Enqueue(logLine);
                if (recentLogs.Count > recentCount)
                {
                    recentLogs.Dequeue();
                }
            }
        }
Ejemplo n.º 40
0
        private void Log(string t, LoggingLevel level = LoggingLevel.Verbose)
        {
            App app = Application.Current as App;

            if (app == null)
            {
                // This occurs in design mode.
                return;
            }
            Logger logger = app.logger;
            if (logger != null)
            {
                logger.Log(t, level);
            }
            else
            {
                Debug.WriteLine("WARNING: Logger not available, log message lost.");
            }
        }
Ejemplo n.º 41
0
        // Called from anywhere to add a new message to the log.
        public static void AddMessage(LoggingLevel logLevel, string logMessage)
        {
            if (IsWithinLevel(logLevel))
            {
                LogEntry logEntry = new LogEntry(logLevel, DateTime.Now, logMessage);

                lock (messageLock)
                {
                    logQueue.Enqueue(logEntry);

                    if (logQueue.Count > logCountLimit)
                    {
                        logQueue.Dequeue();
                    }

                    newLogMessageAvailable = true;
                }
            }
        }
Ejemplo n.º 42
0
        public static char GetLevelTag(LoggingLevel lvl)
        {
            switch (lvl)
            {
            case LoggingLevel.Debug: return('D');

            case LoggingLevel.Info: return('I');

            case LoggingLevel.Warn: return('W');

            case LoggingLevel.Error: return('E');

            case LoggingLevel.Fatal: return('F');

            case LoggingLevel.Exception: return('X');

            default: return('?');
            }
        }
Ejemplo n.º 43
0
        void ILogFormatter.FormatMessage(StringBuilder outStr, Logger logger, LoggingLevel ll, string message)
        {
            outStr.Append('[');
            PutTimeTag(outStr);
            outStr.Append("][");
            outStr.Append(logger.Tag);
            outStr.Append("][");
            outStr.Append(GetLevelTag(ll));
            outStr.Append("]:  ");

            var split = message.Split('\n');

            for (int i = 0; i < split.Length - 1; ++i)
            {
                outStr.Append(split[i]);
                outStr.Append(INDENT_STRING);
            }
            outStr.Append(split[split.Length - 1]);
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Loads a LanguageMap from a URL
        /// Should be called from a CoRoutine to prevent freezing/slowdown
        /// </summary>
        /// <param name="URL">URL to load LanguageMap from</param>
        /// <param name="callBack">CallBack for Download- and Parse-Updates</param>
        /// <returns>String Text (String.Empty if failed)</returns>
        public static void LoadRemoteMap(string URL, Action <CallBackResponse <string> > callBack)
        {
            client         = new WebClient();
            globalCallback = callBack;
            client.DownloadDataCompleted += Client_DownloadFileCompleted;
            // Download file, then save
            LoggingLevel log = LanguageManager.Instance.GetLoggingLevel();

            LoggingLevel.Debug.Log(string.Format("ResourceLoader: Attempting to download LanguageMap from [{0}]", URL), log);

            client.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            client.Encoding = Encoding.UTF8;
            Uri    myUri = new Uri(URL);
            string data  = String.Empty;

            client.DownloadDataAsync(myUri);

            LoggingLevel.Debug.Log("ResourceLoader: [DL] Downloaded Data", log);
        }
Ejemplo n.º 45
0
    public static void Write(string content, LoggingLevel warningLevel)
    {
        var appendTextAction = new Action(() =>
        {
            var text = warningLevel.ToString() + ": " + content + "\n";
            Instance._target.AppendText(text);
        });

        // Only the thread that the Dispatcher was created on may access the
        // DispatcherObject directly. To access a DispatcherObject from a
        // thread other than the thread the DispatcherObject was created on,
        // call Invoke and BeginInvoke on the Dispatcher the DispatcherObject
        // is associated with.
        // You can set the priority to Background, so you guarantee that your
        // key operations will be processed first, and the screen updating
        // operations will happen only after those operations are done.
        Instance._target.Dispatcher.Invoke(appendTextAction,
                                           DispatcherPriority.Background);
    }
Ejemplo n.º 46
0
        static void LoadEditorPrefs()
        {
            if (EditorPrefs.HasKey("MerinoFirstRun") == false)
            {
                SaveEditorPrefs();
                EditorPrefs.SetBool("MerinoFirstRun", true);
            }
            newFileTemplatePath            = EditorPrefs.GetString("MerinoTemplatePath", newFileTemplatePath);
            loggingLevel                   = (LoggingLevel)EditorPrefs.GetInt("MerinoLoggingLevel", (int)LoggingLevel.Warning);
            useYarnSpinnerExperimentalMode = EditorPrefs.GetBool("MerinoExperimentalMode", useYarnSpinnerExperimentalMode);
            validateNodeTitles             = EditorPrefs.GetBool("MerinoValidateNodeTitles", validateNodeTitles);
            useWindowsLineEnding           = EditorPrefs.GetBool("MerinoUseWindowsLinesEnding", useWindowsLineEnding);
            tabSize = EditorPrefs.GetInt("MerinoTabSize", tabSize);

            ColorUtility.TryParseHtmlString(EditorPrefs.GetString("MerinoHighlightCommands"), out highlightCommands);
            ColorUtility.TryParseHtmlString(EditorPrefs.GetString("MerinoHighlightComments"), out highlightComments);
            ColorUtility.TryParseHtmlString(EditorPrefs.GetString("MerinoHighlightNodeOptions"), out highlightNodeOptions);
            ColorUtility.TryParseHtmlString(EditorPrefs.GetString("MerinoHighlightShortcutOptions"), out highlightShortcutOptions);
        }
Ejemplo n.º 47
0
        public void UpdateMaxNumberOfLogs(int maxNumberOfLogs)
        {
            if (MaxNumberOfLogsPerLevel <= maxNumberOfLogs)
            {
                MaxNumberOfLogsPerLevel = maxNumberOfLogs;
                return;
            }

            MaxNumberOfLogsPerLevel = maxNumberOfLogs;
            List <LogViewModel> logsToRemove      = new List <LogViewModel>();
            List <LogViewModel> logsToRemoveTrace = LogsTrace.Take(LogsTrace.Count - maxNumberOfLogs).ToList();

            logsToRemoveTrace.ForEach((m) => { LogsTrace.Remove(m); });
            List <LogViewModel> logsToRemoveDebug = LogsDebug.Take(LogsDebug.Count - maxNumberOfLogs).ToList();

            logsToRemoveDebug.ForEach((m) => { LogsDebug.Remove(m); });
            List <LogViewModel> logsToRemoveInfo = LogsInfo.Take(LogsInfo.Count - maxNumberOfLogs).ToList();

            logsToRemoveInfo.ForEach((m) => { LogsInfo.Remove(m); });
            List <LogViewModel> logsToRemoveWarn = LogsWarn.Take(LogsWarn.Count - maxNumberOfLogs).ToList();

            logsToRemoveWarn.ForEach((m) => { LogsWarn.Remove(m); });
            List <LogViewModel> logsToRemoveError = LogsError.Take(LogsError.Count - maxNumberOfLogs).ToList();

            logsToRemoveError.ForEach((m) => { LogsError.Remove(m); });
            List <LogViewModel> logsToRemoveFatal = LogsFatal.Take(LogsFatal.Count - maxNumberOfLogs).ToList();

            logsToRemoveFatal.ForEach((m) => { LogsFatal.Remove(m); });

            logsToRemove.AddRange(logsToRemoveTrace);
            logsToRemove.AddRange(logsToRemoveDebug);
            logsToRemove.AddRange(logsToRemoveInfo);
            logsToRemove.AddRange(logsToRemoveWarn);
            logsToRemove.AddRange(logsToRemoveError);
            logsToRemove.AddRange(logsToRemoveFatal);

            logsToRemove.ForEach((m) => {
                if (IsActive && LoggingLevel.IsLogLevelAboveMin(m.Level, SelectedMinLogLevel) && IsNamespaceActive(m) && IsSearchCriteriaMatch(m))
                {
                    Logs.Remove(m);
                }
            });
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Depending on the enumparameter we want to define a color
        /// Printout a message with the date, username, the logginglevel and the message
        /// </summary>
        /// <param name="_loggingLevel"></param>
        /// <param name="_message"></param>
        private void LogMessage(LoggingLevel _loggingLevel, string _message)
        {
            ConsoleColor color = Console.ForegroundColor;

            switch (_loggingLevel)
            {
            case LoggingLevel.WARNING:
                Console.ForegroundColor = ConsoleColor.Yellow;
                break;

            case LoggingLevel.ERROR:
                Console.ForegroundColor = ConsoleColor.Red;
                break;
            }

            Console.WriteLine($"{DateTime.Now} | {m_userName} | {_loggingLevel} | {_message}");

            Console.ForegroundColor = color;
        }
Ejemplo n.º 49
0
        protected BaseLogTarget(LogTargetFormat format, LoggingLevel minLoggginLevel)
        {
            targetFormat = format;
            switch (targetFormat)
            {
            case LogTargetFormat.Short:
                getMsg = GetShortMsg;
                break;

            case LogTargetFormat.Extended:
                getMsg = GetExtendedMsg;
                break;

            case LogTargetFormat.ExtendedWithoutDate:
                getMsg = GetExtendedMsgWithoutDate;
                break;
            }
            MinLoggingLevel = minLoggginLevel;
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Writes a freetext log entry according to the current LoggingStyle.
        /// Returns immediately if logging is not initialized or not enabled.
        /// </summary>
        /// <param name="level">The log level for this message.  Messages below LogLevel are ignored.</param>
        /// <param name="msg">The format string to be logged, as in String.Format</param>
        /// <param name="args">Arguments to be formatted.</param>
        private static void Log(LoggingLevel level, string msg, params object[] args)
        {
            if (level < LogLevel)
            {
                return;
            }

            if (!Inited)
            {
                bool initedNow = false;
                switch (LogStyle)
                {
                case LoggingStyle.File:
                    initedNow = initFileLogging();
                    break;

                case LoggingStyle.Console:
                    initedNow = true;
                    break;
                }
                if (!initedNow)
                {
                    return;
                }
            }

            // Go ahead and format the message now.
            msg = String.Format(msg, args);

            int thrd = System.Threading.Thread.CurrentThread.ManagedThreadId;

            switch (LogStyle)
            {
            case LoggingStyle.File:
                logToFile(thrd, msg);
                break;

            case LoggingStyle.Console:
                logToConsole(msg);
                break;
            }
        }
Ejemplo n.º 51
0
        public void Write(
            string text = "",
            LoggingLevel loggingLevel               = LoggingLevel.Verbose,
            [CallerMemberName] string memberName    = "",
            [CallerFilePath] string sourceFilePath  = "",
            [CallerLineNumber] int sourceLineNumber = 0
            )
        {
            WriteLog(
                text,
                loggingLevel,
                memberName,
                sourceFilePath,
                sourceLineNumber
                );

            // Send telemetry for Critical or Error logging events
            switch (loggingLevel)
            {
            case LoggingLevel.Critical:
            case LoggingLevel.Error:
                _telemetryService?.WriteEvent(
                    Enum.GetName(typeof(LoggingLevel), loggingLevel) + "Event",
                    new
                {
                    Text             = text,
                    MemberName       = memberName,
                    SourceFilePath   = sourceFilePath,
                    SourceLineNumber = sourceLineNumber
                });
                break;
            }

            InsertEntry(new LogOutputEventArgs()
            {
                Text             = text,
                LoggingLevel     = loggingLevel,
                CallerMemberName = memberName,
                SourceFilePath   = sourceFilePath,
                SourceLineNumber = sourceLineNumber
            });
        }
Ejemplo n.º 52
0
        public static void Log(string message, LoggingLevel severity = LoggingLevel.Information, bool returnline = true)
        {
            lock (lockObj)
            {
                if (message == "")
                {
                    Console.WriteLine();
                    return;
                }

                var msg = "";

                switch (severity)
                {
                case LoggingLevel.Warning:
                    msg = "  Warning  ";
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;

                case LoggingLevel.Error:
                    msg = "   Error   ";
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;

                case LoggingLevel.Information:
                    msg = "Information";
                    Console.ForegroundColor = ConsoleColor.White;
                    break;
                }

                if (returnline)
                {
                    Console.WriteLine(DateTime.Now.ToString("'['HH':'mm':'ss']'") + "[" + msg + "] " + message);
                }
                else
                {
                    Console.Write("\r" + DateTime.Now.ToString("'['HH':'mm':'ss']'") + "[" + msg + "] " + message);
                }

                Console.ForegroundColor = ConsoleColor.White;
            }
        }
Ejemplo n.º 53
0
        public static void Log(LoggingLevel level, string initialText)
        {
            if (level < SelectedLoggingLevel)
            {
                return;
            }

            var text = "[Rider] [" + level + "] " + initialText;

            switch (level)
            {
            case LoggingLevel.Warning:
                Debug.LogWarning(text);
                break;

            default:
                Debug.Log(text);
                break;
            }
        }
Ejemplo n.º 54
0
        private static void LogBase(ILog log, LoggingLevel loggingLevel, string message, object loggingProperties, Exception exception)
        {
            if (ShouldLog(log, loggingLevel))
            {
                PushLoggingProperties(loggingProperties);
                switch (loggingLevel)
                {
                case LoggingLevel.Debug: log.Debug(message, exception); break;

                case LoggingLevel.Info: log.Info(message, exception); break;

                case LoggingLevel.Warning: log.Warn(message, exception); break;

                case LoggingLevel.Error: log.Error(message, exception); break;

                case LoggingLevel.Fatal: log.Fatal(message, exception); break;
                }
                PopLoggingProperties(loggingProperties);
            }
        }
Ejemplo n.º 55
0
        public void Log(LoggingLevel level, object obj, Exception exception)
        {
            // If exception is null, use log method without exception
            if (exception == null)
            {
                Log(level, obj);
                return;
            }

            // Map topshelf loglevel to liblog loglevel
            var logLevel = MapLogLevel(level);

            // Don't log anything if loglevel is not specified
            if (logLevel == null)
            {
                return;
            }

            _logger.Log(logLevel.Value, () => FormatObject(obj), exception);
        }
Ejemplo n.º 56
0
        public static void Log(LoggingLevel level, string initialText)
        {
            if (level < SelectedLoggingLevel)
            {
                return;
            }

            var text = "[Rider] " + DateTime.Now.ToString("HH:mm:ss:ff") + " [" + level + "] " + initialText;

            switch (level)
            {
            case LoggingLevel.Warning:
                Debug.LogWarning(text);
                break;

            default:
                Debug.Log(text);
                break;
            }
        }
Ejemplo n.º 57
0
        public void Log(LoggingLevel loggingLevel, string information, params object[] arguments)
        {
            switch (loggingLevel)
            {
            case LoggingLevel.Warning:
                Console.ForegroundColor = ConsoleColor.Red;
                break;

            case LoggingLevel.Info:
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                break;

            default:
                Console.ResetColor();
                break;
            }

            Console.WriteLine("{0} - {1}", _lineNumber++, string.Format(information, arguments));
            Console.ResetColor();
        }
        public void Log(LoggingLevel level, string msg)
        {
            if (level >= LoggingLevel.Information)
            {
                string fullMsg = level.ToString() + ": " + msg;
                CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    StatusList.Items.Insert(0, fullMsg);
                });

                /*
                 * // ToDo: scrolling doesn't take place correctly.
                 * StatusList.Items.Add(fullMsg);
                 * StatusList.SelectedIndex = StatusList.Items.Count - 1;
                 * StatusList.UpdateLayout();
                 * StatusList.ScrollIntoView(StatusList.SelectedItem, ScrollIntoViewAlignment.Leading);
                 */
            }
            Microsoft.Devices.Management.Logger.Log(msg, LoggingLevel.Verbose);
        }
Ejemplo n.º 59
0
        protected void WriteLine(string newstring, LoggingLevel requestedLevel = LoggingLevel.Standard)
        {
            if (outputs.Count < 1)
            {
                AddDefaultOutput();
            }

            foreach (output thisOutput in outputs)
            {
                if (thisOutput.Allows(requestedLevel))
                {
                    thisOutput.OutputWriter.WriteLine(newstring);
                }
            }

            if (autoFlush)
            {
                Flush();
            }
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Logs a message directly without checking ShouldLog.
        /// </summary>
        /// <param name="message">Message to be written to the log.</param>
        /// <param name="level">The level of logging to be performed.</param>
        /// <param name="category">The category that this message belongs to.</param>
        protected override void LogMessage(LoggingLevel level, string category, string message)
        {
            var severityLevel = LoggingLevelToSeverityLevel(level);

            if (severityLevel != null)
            {
                if (level == LoggingLevel.Debug)
                {
                    _telemetryClient.TrackTrace(message, severityLevel.Value, GetAllProperties(level, category));
                }
                else if (level == LoggingLevel.Error)
                {
                    _telemetryClient.TrackException(new Exception(message), GetAllProperties(level, category));
                }
                else
                {
                    _telemetryClient.TrackEvent(message, GetAllProperties(level, category));
                }
            }
        }