Пример #1
0
        private void ValidateCall(LoggerLevel level, String expectedMessage, Exception expectedException)
        {
            stream.Seek(0, SeekOrigin.Begin);

            StreamReader reader = new StreamReader(stream);
            String       line   = reader.ReadLine();

            Match match = Regex.Match(line, @"^\[(?<level>[^]]+)\] '(?<name>[^']+)' (?<message>.*)$");

            Assert.IsTrue(match.Success, "StreamLogger.Log did not match the format");
            Assert.AreEqual(Name, match.Groups["name"].Value, "StreamLogger.Log did not write the correct Name");
            Assert.AreEqual(level.ToString(), match.Groups["level"].Value, "StreamLogger.Log did not write the correct Level");
            Assert.AreEqual(expectedMessage, match.Groups["message"].Value, "StreamLogger.Log did not write the correct Message");

            line = reader.ReadLine();

            if (expectedException == null)
            {
                Assert.IsNull(line);
            }
            else
            {
                match = Regex.Match(line, @"^\[(?<level>[^]]+)\] '(?<name>[^']+)' (?<type>[^:]+): (?<message>.*)$");

                Assert.IsTrue(match.Success, "StreamLogger.Log did not match the format");
                Assert.AreEqual(Name, match.Groups["name"].Value, "StreamLogger.Log did not write the correct Name");
                Assert.AreEqual(level.ToString(), match.Groups["level"].Value, "StreamLogger.Log did not write the correct Level");
                Assert.AreEqual(expectedException.GetType().FullName, match.Groups["type"].Value, "StreamLogger.Log did not write the correct Exception Type");
                // Assert.AreEqual(expectedException.Message, match.Groups["message"].Value, "StreamLogger.Log did not write the correct Exception Message");
            }
        }
Пример #2
0
        protected override void Log(LoggerLevel level, String name, String message, Exception exception)
        {
            writer.WriteLine("[{0}] '{1}' {2}", level.ToString(), name, message);

            if (exception != null)
            {
                if (exception.StackTrace != null)
                {
                    writer.WriteLine("[{0}] '{1}' {2}: {3}\n{4}",
                                     level.ToString(),
                                     name,
                                     exception.GetType().FullName,
                                     exception.Message,
                                     exception.StackTrace);
                }
                else
                {
                    writer.WriteLine("[{0}] '{1}' {2}: {3}",
                                     level.ToString(),
                                     name,
                                     exception.GetType().FullName,
                                     exception.Message);
                }
            }
        }
        /// <summary>
        /// A Common method to log.
        /// </summary>
        /// <param name="level">The level of logging</param>
        /// <param name="name">The name of the logger</param>
        /// <param name="message">The Message</param>
        /// <param name="exception">The Exception</param>
        protected override void Log(LoggerLevel level, String name, String message, Exception exception)
        {
            Console.Out.WriteLine(string.Format("[{0}] '{1}' {2}", level.ToString(), name, message));

            if (exception != null)
            {
                Console.Out.WriteLine("[{0}] '{1}' {2}: {3} {4}", level.ToString(), name, exception.GetType().FullName, exception.Message, exception.StackTrace);
            }
        }
Пример #4
0
		/// <summary>
		/// A Common method to log.
		/// </summary>
		/// <param name="level">The level of logging</param>
		/// <param name="name">The name of the logger</param>
		/// <param name="message">The Message</param>
		/// <param name="exception">The Exception</param>
		protected override void Log(LoggerLevel level, String name, String message, Exception exception)
		{
			Console.Out.WriteLine(string.Format("[{0}] '{1}' {2}", level.ToString(), name, message));

			if (exception != null)
			{
				Console.Out.WriteLine("[{0}] '{1}' {2}: {3} {4}", level.ToString(), name, exception.GetType().FullName,
				                      exception.Message, exception.StackTrace);
			}
		}
Пример #5
0
        /// <summary>
        /// A Common method to log.
        /// </summary>
        /// <param name="level">The level of logging</param>
        /// <param name="message">The Message</param>
        /// <param name="exception">The Exception</param>
        protected void Log(LoggerLevel level, String message, Exception exception)
        {
            TraceContext ctx = HttpContext.Current.Trace;

            if (_logLevel <= level && ctx.IsEnabled)
            {
                ctx.Write(String.Format("[{0}]", level.ToString()), String.Format("{0} {1}", _name, message));

                if (exception != null)
                {
                    ctx.Warn(String.Format("[{0}]", level.ToString()), String.Format("{0} {1}", exception.Message, exception.StackTrace));
                }
            }
        }
Пример #6
0
        /// <summary>
        /// Habilita el proveedor de email para el logeo de errores.
        /// </summary>
        /// <param name="userName">Nombre del usuario.</param>
        /// <param name="password">Contraseña del usuario.</param>
        /// <param name="server">Servidor del proveedor de correo.</param>
        /// <param name="from">Email de quien envia el correo. </param>
        /// <param name="to">Email del destinatario.</param>
        /// <param name="enableSsl">Envio de email con Ssl.</param>
        /// <param name="port">Puerto del proveedor de envio de email.</param>
        /// <param name="subject">Asunto del email.</param>
        /// <param name="isBodyHtml">Si esta habilitado el cuerpo del correo con Html.</param>
        /// <param name="loggerMinimumLevel">El nivel mínimo de error.</param>
        /// <param name="outputTemplate">Plantilla de salida.</param>
        /// <returns>La clase SerilogOptions.</returns>
        public SerilogOptions AddEmail(
            string userName,
            string password,
            string server,
            string from,
            string to,
            bool enableSsl  = SerilogEmailSettings.DefaultEnableSsl,
            int port        = SerilogEmailSettings.DefaultPort,
            string subject  = SerilogEmailSettings.DefaultSubject,
            bool isBodyHtml = SerilogEmailSettings.DefaultIsBodyHtml,
            LoggerLevel loggerMinimumLevel = SerilogEmailSettings.DefaultMinimumLevel,
            string outputTemplate          = SerilogEmailSettings.DefaultOutputTemplate)
        {
            this.SerilogSettings.Email = new SerilogEmailSettings
            {
                UserName       = userName,
                Password       = password,
                Server         = server,
                From           = from,
                To             = to,
                EnableSsl      = enableSsl,
                Port           = port,
                Subject        = subject,
                IsBodyHtml     = isBodyHtml,
                MinimumLevel   = loggerMinimumLevel.ToString(),
                OutputTemplate = outputTemplate,
                Enabled        = true,
            };

            return(this);
        }
Пример #7
0
        public void WriteLog(LoggerLevel level,
                             string message)
        {
            _lock.WaitOne();
            var           nTime = DateTime.Now;
            StringBuilder sb    = new StringBuilder();

            sb.AppendFormat("[时间]:{0}\r\n", nTime.ToString(DATE_TIME_FORMAT));
            sb.AppendFormat("[级别]:{0}\r\n", level.ToString());
            sb.AppendFormat("[消息]:{0}\r\n", message);
            sb.Append("\r\n");
            string timeStamp = DateTime.Now.ToString(FILENAME_DATE_FORMAT);
            string fullPath  = Path.Combine(LogDir, timeStamp + ".log");

            File.AppendAllText(fullPath, sb.ToString());
            if (_checkTime == DateTime.MinValue)
            {
                _checkTime = nTime;
            }
            if ((nTime - _checkTime).TotalHours >= 1)
            {
                //每隔一小时检查日志文件
                ThreadPool.QueueUserWorkItem(CheckLogs);
                _checkTime = nTime;
            }
            _lock.Release();
        }
Пример #8
0
        protected virtual bool WriteLogMsg
            (LoggerLevel level,
            string msg)
        {
            lock (this) {
                // Fail if logger hasn't been started
                if (_loggerState == LoggerState.Stopped)
                {
                    return(false);
                }

                // Ignore message logging is paused or it doesn't pass the filter
                if ((_loggerState == LoggerState.Paused) || ((_levels & (uint)level) != (uint)level))
                {
                    return(true);
                }

                // Write log message
                DateTime tmNow  = DateTime.Now;
                string   logMsg = String.Format("{0} {1}  {2}: {3}",
                                                tmNow.ToShortDateString(), tmNow.ToLongTimeString(),
                                                level.ToString().Substring(0, 1), msg);
                _logFile.WriteLine(logMsg);
                return(true);
            }
        }
Пример #9
0
        public void Log(String logMessage, LoggerLevel messageLevel, params ComponentType[] messageComponentTypes)
        {
            if (messageLevel < _logThreshholdLevel) { return; }

            string date = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
            string level = messageLevel == LoggerLevel.NULL ? "   " : messageLevel.ToString();
            string type = messageComponentTypes[0] == ComponentType.NULL ? "   " : ComponentTypeUtil.GetCodeFromType(messageComponentTypes[0]);

            // If no component types are specified, log everything.
            if (componentTypesToLog == null || componentTypesToLog.Count == 0)
            {
                _streamWriter.WriteLine(date + " | " + level + " | " + type + " | " + logMessage);
                _streamWriter.Flush();
                return;
            }
            else // Else, only log messages matching one of the specified component types.
            {
                foreach (ComponentType componentType in messageComponentTypes)
                {
                    if (componentTypesToLog.Contains(componentType))
                    {
                        _streamWriter.WriteLine(date + " | " + level + " | " + type + " | " + logMessage);
                        _streamWriter.Flush();
                        return;
                    }
                }
            }
        }
Пример #10
0
 protected virtual string CreateLogLine(string format, object[] pars, LoggerLevel level)
 {
     return(string.Format("{0}  {1,-10} {2}",
                          DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss.ff"),
                          "(" + level.ToString() + ")",
                          pars != null ? string.Format(format, pars) : (format != null ? format : "")));
 }
 // ----------------------------------------------------------------------
 protected override void Output( LoggerLevel level, object message, Exception exception )
 {
     buffer.Append( level.ToString() );
     buffer.Append( ": " );
     buffer.AppendLine( message == null ? "null" : message.ToString() );
     Output( exception );
 }
Пример #12
0
        }         // Clear

        // ----------------------------------------------------------------------
        protected override void Output(LoggerLevel level, object message, Exception exception)
        {
            buffer.Append(level.ToString());
            buffer.Append(": ");
            buffer.AppendLine(message == null ? "null" : message.ToString());
            Output(exception);
        }         // Output
        public void Output(LoggerLevel level, string content)
        {
            var color = Console.ForegroundColor;

            switch (level)
            {
            case LoggerLevel.Info:
                Console.ForegroundColor = ConsoleColor.Green;
                break;

            case LoggerLevel.Warning:
                Console.ForegroundColor = ConsoleColor.Yellow;
                break;

            case LoggerLevel.Error:
                Console.ForegroundColor = ConsoleColor.Red;
                break;

            case LoggerLevel.Message:
                Console.ForegroundColor = ConsoleColor.Blue;
                break;

            default:
                break;
            }
            Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss.fff")} [{level.ToString()}] - {content}");
            Console.ForegroundColor = color;
        }
Пример #14
0
        static public void writeToLog(LoggerLevel level, string text)
        {
            try
            {
                string path = Logger.physicalPath;

                if (!Directory.Exists(path))    //DirectoryServices object
                {
                    Directory.CreateDirectory(path);
                }

                //normalize date format to 00/00/0000
                string day   = (DateTime.Today.Day < 10) ? "0" + DateTime.Today.Day.ToString() : DateTime.Today.Day.ToString();
                string month = (DateTime.Today.Month < 10) ? "0" + DateTime.Today.Month.ToString() : DateTime.Today.Month.ToString();
                string year  = DateTime.Today.Year.ToString();


                Environment.CurrentDirectory = path;
                SR = File.AppendText(day + "_" + month + "_" + year + ".log");   // if exists ->add     else -> create and add

                if (SR != null)
                {
                    SR.WriteLine(DateTime.Now + " " + level.ToString() + " [" + System.Threading.Thread.CurrentThread.ManagedThreadId + "]" + "\t " + text);
                    SR.Close();
                }
                //DBservicesA dbs = new DBservices();
                //string CleanText = text.Replace("'", "''");
                //dbs.insertExaption(CleanText);
            }
            catch
            {
            }
        }
Пример #15
0
        public void Should_Log_To_File([Values] LoggerLevel loggerLevel)
        {
            var message = string.Format("Log {0} message from Integration Tests", loggerLevel.ToString());

            LoggerHelper.Log(message, loggerLevel);
            string actualResult = GetTextInLogFile();

            Assert.IsTrue(actualResult.Contains(message));
        }
Пример #16
0
        private string LogItemWorker(LoggerLevel level, string text)
        {
            //string msg = string.Format("{0}: {1}", DateTime.Now, text);
            string msg = string.Format("{0}: {1}", DateTime.Now, level.ToString() + "-" + text);

            ILog.Log(level, text);

            return(msg);
        }
Пример #17
0
 protected virtual string CreateLogMessage(string loggerName, LoggerLevel level, string message)
 {
     return(string.Format(Thread.CurrentThread.CurrentCulture, "{0}: {1}: {2}: {3}",
                          DateTime.Now.ToString("dd.MM.yyyy HH.mm.ss", Thread.CurrentThread.CurrentCulture),
                          loggerName,
                          level.ToString().Substring(0, 1),
                          message
                          ));
 }
Пример #18
0
 /// <summary>
 /// Save method name and params of method based on type passed
 /// </summary>
 /// <param name="methodName">Name of method who fire this</param>
 /// <param name="param">Params of method</param>
 public static void LogOuterParams(LoggerLevel level, string methodName, string param)
 {
     LoggerBC.Instance.LogDataToCloud(new LogData()
     {
         Id         = "0",
         Type       = level.ToString(),
         MethodName = methodName,
         Param      = param
     });
 }
Пример #19
0
 /// <summary>
 /// Save method name and params of method based on type passed
 /// </summary>
 /// <param name="methodName">Name of method who fire this</param>
 /// <param name="param">Params of method</param>
 public static void LogExceptionParams(LoggerLevel level, string methodName, Exception ex)
 {
     LoggerBC.Instance.LogDataToCloud(new LogData()
     {
         Id         = "0",
         Type       = level.ToString(),
         MethodName = methodName,
         Param      = ex.Message
     });
 }
Пример #20
0
 static void WriteCore(LoggerLevel level,
                       LogErrorCode lec,
                       string message)
 {
     Console.WriteLine("LOG: {3:u} {0,5} - {1} - {2}",
                       level.ToString().ToUpper(),
                       lec,
                       message,
                       DateTime.Now);
 }
Пример #21
0
        public static void Append(string message, string name = "", string module = "", LoggerLevel logType = LoggerLevel.Debug, bool logTypeDist = false)
        {
            if (string.IsNullOrEmpty(_rootPath))
            {
                _rootPath = AppDomain.CurrentDomain.BaseDirectory + "Log";
                FileHelper.CreateFloder(_rootPath);
            }
            var path = _rootPath + "/" + DateTime.Now.ToString("yyyy-MM-dd");

            FileHelper.CreateFloder(path);

            DelLog();

            var fileName = logTypeDist ? GetName(name, logType.ToString()) : GetName(name);
            var logFile  = Path.Combine(path, fileName);

            var content = GetLogWithTime(module, message, logType.ToString());

            Console.WriteLine(content);
            FileHelper.Append(logFile, content);
        }
Пример #22
0
        private static void Log(LoggerLevel level, string message)
        {
            if (LogLevel < level)
            {
                return;
            }

            lock (locker)
                File.AppendAllText(LogFile, string.Format(CultureInfo.InvariantCulture, "[{0}] [{1}] - {2}\r\n",
                                                          level.ToString().ToUpperInvariant(),
                                                          DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss", CultureInfo.InvariantCulture),
                                                          message));
        }
Пример #23
0
        /// <summary>
        /// Habilita el proveedor de archivos para el logeo de errores.
        /// </summary>
        /// <param name="filePath">Ruta donde se crearán los archivos.</param>
        /// <param name="minimumLevel">Nivel mínimo de error habilidato por defecto.</param>
        /// <param name="interval">Intervalo para la creaciñon de archivos.</param>
        /// <returns>La clase SerilogOptions.</returns>
        public SerilogOptions AddFile(
            string filePath             = SerilogFileSettings.DefaultFilePath,
            LoggerLevel minimumLevel    = SerilogFileSettings.DefaultMinimumLevel,
            LoggerFileInterval interval = SerilogFileSettings.DefaultLoggerInterval)
        {
            this.SerilogSettings.File = new SerilogFileSettings
            {
                FilePath     = filePath,
                MinimumLevel = minimumLevel.ToString(),
                Interval     = interval.ToString(),
                Enabled      = true,
            };

            return(this);
        }
Пример #24
0
        /// <summary>
        /// Habilita el proveedor de consola para el logeo de errores.
        /// </summary>
        /// <param name="minimumLevel">Nivel mínimo de error habilidato por defecto.</param>
        /// <param name="outputTemplate">Plantilla de salida por defecto.</param>
        /// <returns>La clase SerilogOptions.</returns>
        public SerilogOptions AddConsole(
            LoggerLevel minimumLevel = SerilogConsoleSettings.DefaultMinimumLevel,
            string outputTemplate    = SerilogConsoleSettings.DefaultOutputTemplate)
        {
            this.SerilogSettings.Console = new SerilogConsoleSettings
            {
                MinimumLevel = minimumLevel.ToString(),

                OutputTemplate = outputTemplate,

                Enabled = true,
            };

            return(this);
        }
Пример #25
0
        // Writing log to Console
        private void PrintLog(LoggerLevel level, string message, string location, string userId = null)
        {
            ConsoleColor foregroundColor, backgroundColor;

            switch (level)
            {
            case LoggerLevel.dbug:
                foregroundColor = ConsoleColor.Gray;
                backgroundColor = default;
                break;

            case LoggerLevel.info:
                foregroundColor = ConsoleColor.Green;
                backgroundColor = default;
                break;

            case LoggerLevel.fail:
                foregroundColor = ConsoleColor.White;
                backgroundColor = ConsoleColor.Red;
                break;

            default:
                foregroundColor = default;
                backgroundColor = default;
                break;
            }

            Console.ForegroundColor = foregroundColor;
            Console.BackgroundColor = backgroundColor;
            Console.Write(level.ToString());
            Console.ResetColor();
            Console.Write(": ");

            Console.WriteLine(location);
            Console.Write($"\t{message}");

            if (!string.IsNullOrEmpty(userId))
            {
                Console.WriteLine($"\tuserId: {userId}");
            }
            else
            {
                Console.WriteLine();
            }
        }
Пример #26
0
        /// <summary>
        /// Habilita el proveedor de SqlServer para el logeo de errores.
        /// </summary>
        /// <param name="connectionString">Conexión de la base de datos donde se guardaran los errores.</param>
        /// <param name="schemaName">Nombre del esquema de la tabla donde se guardaran los erroreso.</param>
        /// <param name="tableName">Nombre de la tabla donde se guardaran los errores.</param>
        /// <param name="autoCreateDb">Si se debe crear la DB.</param>
        /// <param name="loggerMinimumLevel">El nivel mínimo de error.</param>
        /// <returns>La clase SerilogOptions.</returns>
        public SerilogOptions AddSqlServer(
            string connectionString,
            string schemaName = SerilogSqlServerSettings.DefaultSchemaName,
            string tableName  = SerilogSqlServerSettings.DefaultTableName,
            bool autoCreateDb = SerilogSqlServerSettings.DefaultAutoCreateDB,
            LoggerLevel loggerMinimumLevel = SerilogEmailSettings.DefaultMinimumLevel)
        {
            this.SerilogSettings.SqlServer = new SerilogSqlServerSettings
            {
                ConnectionString = connectionString,
                SchemaName       = schemaName,
                TableName        = tableName,
                MinimumLevel     = loggerMinimumLevel.ToString(),
                AutoCreateDB     = autoCreateDb,
                Enabled          = true,
            };

            return(this);
        }
Пример #27
0
        private void writeLog(LoggerLevel level, string m, string s, int lineNumber, string fileName)
        {
            var content = $"[{DateTime.Now.ToString("HH:mm:ss.fff")}]{m}[{level.ToString()}],{System.IO.Path.GetFileName(fileName)}({lineNumber}):{s}";

            if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "log.ini"))
            {
                LoggerLevel userLevel = LoggerLevel.DEBUG;
                try
                {
                    StringBuilder sbConfig = new StringBuilder(1024);
                    GetPrivateProfileString("", "level", "INFO", sbConfig, 1024, @"log.ini");
                    if (sbConfig.ToString().Length > 0)
                    {
                        Enum.TryParse(sbConfig.ToString(), out userLevel);
                    }
                }
                catch { }
                Console.WriteLine(content);
                if ((int)level >= (int)userLevel)
                {
                    string path = string.Format(@"{2}log\{0}_{1}.log", "myWindowsService", DateTime.Now.ToString("yyyyMMdd"), System.AppDomain.CurrentDomain.BaseDirectory);
                    writeFileLog(path, content);
                }
            }
            else
            {
                try
                {
                    Console.WriteLine(content);
#if UDP_LOG
                    UdpClient  udpClient   = new UdpClient();
                    byte[]     sendData    = Encoding.Default.GetBytes(content);
                    IPEndPoint targetPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8889);
                    udpClient.Send(sendData, sendData.Length, targetPoint);
#endif
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
Пример #28
0
		/// <summary>
		/// A Common method to log.
		/// </summary>
		/// <param name="level">The level of logging</param>
		/// <param name="name">The Log name.</param>
		/// <param name="message">The Message</param>
		/// <param name="exception">The Exception</param>
		protected override void Log(LoggerLevel level, String name, String message, Exception exception)
		{
			TraceContext ctx = HttpContext.Current.Trace;

			if (ctx.IsEnabled)
			{
				String category = String.Format("[{0}]", level.ToString());
				String formattedMessage = String.Format("{0} {1}", name, message);

				ctx.Write(category, formattedMessage);

				if (exception != null)
				{
					formattedMessage = String.Format("{0}: {1} {2}Stack Trace: {3}",
					                                 exception.GetType(), exception.Message, Environment.NewLine, exception.StackTrace);

					ctx.Warn(category, formattedMessage);
				}
			}
		}
Пример #29
0
        protected void Log(LoggerLevel loggerLevel, string loggerName, string message, Exception exception)
        {
            switch (loggerLevel)
            {
            case LoggerLevel.Debug:
                break;

            case LoggerLevel.Error:
                ErrorCount++;
                break;

            case LoggerLevel.Fatal:
                break;

            case LoggerLevel.Info:
                break;

            case LoggerLevel.Off:
                break;

            case LoggerLevel.Warn:
                break;

            default:
                break;
            }
            TextWriter output = Console.Out;

            if (loggerLevel == LoggerLevel.Error)
            {
                output = Console.Error;
            }

            output.WriteLine("[{0}] '{1}' {2}", loggerLevel, loggerName, message);
            if (exception != null)
            {
                output.WriteLine("[{0}] '{1}' {2}: {3} {4}", new object[] { loggerLevel.ToString(), loggerName, exception.GetType().FullName, exception.Message, exception.StackTrace });
            }
            Logs.Add(new TestLog(loggerLevel, message));
        }
Пример #30
0
		/// <summary>
		/// A Common method to log.
		/// </summary>
		/// <param name="loggerLevel">The level of logging</param>
		/// <param name="loggerName">The Log name.</param>
		/// <param name="message">The Message</param>
		/// <param name="exception">The Exception</param>
		protected override void Log(LoggerLevel loggerLevel, String loggerName, String message, Exception exception)
		{
			TraceContext ctx = TryToGetTraceContext();
			if (ctx == null)
				return;

			if (ctx.IsEnabled)
			{
				String category = String.Format(CultureInfo.CurrentCulture, "[{0}]", loggerLevel.ToString());
				String formattedMessage = String.Format(CultureInfo.CurrentCulture, "{0} {1}", loggerName, message);

				ctx.Write(category, formattedMessage);

				if (exception != null)
				{
					formattedMessage = String.Format(CultureInfo.CurrentCulture, "{0}: {1} {2}Stack Trace: {3}",
					                                 exception.GetType(), exception.Message, Environment.NewLine, exception.StackTrace);

					ctx.Warn(category, formattedMessage);
				}
			}
		}
Пример #31
0
        /// <summary>
        /// Write a message to the log file
        /// </summary>
        /// <param name="message">Message</param>
        /// <param name="source">Source (subsystem)</param>
        /// <param name="level">Log-level</param>
        public static void Write(string message, SubSystem source, LoggerLevel level = LoggerLevel.Info)
        {
            Debug.WriteLine(level.ToString() + ": " + message);

            if (!m_LoggerIsDisabled)                                                     //TODO: Testen was passiert wenn der Logger aus ist (SocketListener Problem!)
            {
                if (level >= m_MinimumLogLevel && !m_ExcludedSubSystems.HasFlag(source)) //Limit log depth
                {
                    if (m_MessageQueue == null)
                    {
                        m_MessageQueue = new ConcurrentQueue <LogMessage>();
                    }

                    m_MessageQueue.Enqueue(new LogMessage(message, level, source));

                    if (m_Worker == null || !m_Worker.IsBusy)
                    {
                        StartBackgroundWorker();
                    }
                }
            }
        }
Пример #32
0
        private void AddLogFile(LoggerLevel level, string message, int code)
        {
            if (strLogFilePath == null || strLogFilePath.Length == 0)
            {
                throw new ApplicationException("no log file path specified");
            }
            //If the log file path is not empty but the file is not available it will create it
            if (false == File.Exists(strLogFilePath))
            {
                if (false == CheckDirectory(strLogFilePath))
                {
                    throw new ApplicationException("problems with log file path");
                }
                FileStream fs = new FileStream(strLogFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                fs.Close();
            }
            Exception last_exception = null;
            StreamWriter sw = null;
            for (int timeout = 0; timeout < 30; timeout++)
            {
                try
                {
                    sw = new StreamWriter(strLogFilePath, true);
                    if (sw != null) break;
                }
                catch (Exception ex)
                {
                    last_exception = ex;
                    sw = null;
                }
                Thread.Sleep(100);
            }
            if (sw == null)
            {
                // MessageBox.Show("can't open log file: " + last_exception.Message);
                throw new Exception("can't open log file: " + last_exception.Message);
            }

            StringBuilder line = new StringBuilder();
            line.Append(DateTime.Now.ToString("u"));
            line.Append(" ");
            line.Append(m_source);
            line.Append(" ");
            line.Append(level.ToString());
            line.Append(" ");
            line.Append(message);
            if (code != 0)
            {
                line.Append(" (code=");
                line.Append(code.ToString());
                line.Append(")");
            }

            sw.WriteLine(line.ToString());

            sw.Flush();
            sw.Close();
        }
Пример #33
0
 public static void Log(string callingClass, LoggerLevel level, string message)
 {
     System.Diagnostics.Debug.WriteLine($"{level.ToString()} [{callingClass}] {message}");
     Console.WriteLine($"{level.ToString()} [{callingClass}] {message}");
 }
Пример #34
0
        public void Warn(string message, Exception exception)
        {
            Log(LoggerLevel.Warn, message, exception);
        }

        /// <summary>
        /// Logs an warn message.
        /// </summary>
        /// <param name="format">Message format</param>
        /// <param name="args">Array of objects to write using format</param>
        public void Warn( string format, params Object[] args )
Пример #35
0
 // ----------------------------------------------------------------------
 public static string Format( LoggerLevel value )
 {
     return value.ToString();
 }
Пример #36
0
		private void ValidateCall(LoggerLevel level, String expectedMessage, Exception expectedException)
		{
			stream.Seek(0, SeekOrigin.Begin);
			
			StreamReader reader = new StreamReader(stream);
			String line = reader.ReadLine();

			Match match = Regex.Match(line, @"^\[(?<level>[^]]+)\] '(?<name>[^']+)' (?<message>.*)$");

			Assert.IsTrue(match.Success, "StreamLogger.Log did not match the format");
			Assert.AreEqual(Name, match.Groups["name"].Value, "StreamLogger.Log did not write the correct Name");
			Assert.AreEqual(level.ToString(), match.Groups["level"].Value, "StreamLogger.Log did not write the correct Level");
			Assert.AreEqual(expectedMessage, match.Groups["message"].Value, "StreamLogger.Log did not write the correct Message");

			line = reader.ReadLine();
			
			if (expectedException == null)
			{
				Assert.IsNull(line);
			}
			else
			{
				match = Regex.Match(line, @"^\[(?<level>[^]]+)\] '(?<name>[^']+)' (?<type>[^:]+): (?<message>.*)$");

				Assert.IsTrue(match.Success, "StreamLogger.Log did not match the format");
				Assert.AreEqual(Name, match.Groups["name"].Value, "StreamLogger.Log did not write the correct Name");
				Assert.AreEqual(level.ToString(), match.Groups["level"].Value, "StreamLogger.Log did not write the correct Level");
				Assert.AreEqual(expectedException.GetType().FullName, match.Groups["type"].Value, "StreamLogger.Log did not write the correct Exception Type");
				// Assert.AreEqual(expectedException.Message, match.Groups["message"].Value, "StreamLogger.Log did not write the correct Exception Message");
			}
		}
Пример #37
0
		public bool RecordedMessage(LoggerLevel level, string message)
		{
			return messages.Contains(level.ToString().ToUpper() + ": " + message);
		}
Пример #38
0
 private static void RegisterLoggers(LoggerLevel loggerLevel)
 {
     Container.Register(
         Component.For(typeof(ILogger))
             .ImplementedBy(typeof(ConsoleLogger))
             .Parameters(Parameter.ForKey("loglevel").Eq(loggerLevel.ToString()))
             .LifeStyle.Is(LifestyleType.Singleton));
 }
Пример #39
0
 public void Log(string strLogMessage, LoggerLevel level)
 {
     lock (this) {
         string strType = System.Configuration.ConfigurationManager.AppSettings["logType"];
         switch (strType) {
             case "eventlog":
                 EventLogEntryType et;
                 switch (level) {
                     case LoggerLevel.Error:
                         et = EventLogEntryType.Error;
                         break;
                     case LoggerLevel.Information:
                         et = EventLogEntryType.Information;
                         break;
                     case LoggerLevel.Warning:
                         et = EventLogEntryType.Warning;
                         break;
                     default:
                         et = EventLogEntryType.Information;
                         break;
                 }
                 StampEventLogEntry(strLogMessage, et);
                 break;
             case "xml":
                 StampXmlLogEntry(strLogMessage, level);
                 break;
             default:
                 string strFile = "";
                 try {
                     strFile = System.Configuration.ConfigurationManager.AppSettings["logFile"];
                 } catch (System.Configuration.SettingsPropertyNotFoundException) {
                     strFile = System.Environment.CurrentDirectory + "\\debug.log";
                 }
                 if (strFile == "") {
                     strFile = System.Environment.CurrentDirectory + "\\debug.log";
                 } else {
                     strFile = System.Environment.CurrentDirectory + "\\" + strFile;
                 }
                 StreamWriter objLogFile = File.AppendText(strFile);
                 objLogFile.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss.ffffff") + "|" + level.ToString() + "|" + strLogMessage);
                 objLogFile.Close();
                 break;
         }
     }
 }
Пример #40
0
		protected override void Log(LoggerLevel loggerLevel, string loggerName, string message, Exception exception)
		{
			if (eventLog == null) return; // just in case it was disposed

			EventLogEntryType type = TranslateLevel(loggerLevel);

			String contentToLog;

			if (exception == null)
			{
				contentToLog = string.Format(CultureInfo.CurrentCulture, "[{0}] '{1}' message: {2}", loggerLevel.ToString(), loggerName, message);
			}
			else
			{
				contentToLog = string.Format(CultureInfo.CurrentCulture, "[{0}] '{1}' message: {2} exception: {3} {4} {5}",
				                             loggerLevel.ToString(), loggerName, message, exception.GetType(), exception.Message,
				                             exception.StackTrace);
			}

			eventLog.WriteEntry(contentToLog, type);
		}
Пример #41
0
 public static void Log(string callingClass, LoggerLevel level, string message)
 {
     Console.WriteLine($"{level.ToString()} [{callingClass}] {message}");
 }
Пример #42
0
 public bool RecordedMessage(LoggerLevel level, string message)
 {
     return(messages.Contains(level.ToString().ToUpper() + ": " + message));
 }
Пример #43
0
        private void AddLogFile(LoggerLevel level, string message, int code)
        {
            if (strLogFilePath == null || strLogFilePath.Length == 0)
            {
                throw new ApplicationException("no log file path specified");
            }
            //If the log file path is not empty but the file is not available it will create it
            if (false == File.Exists(strLogFilePath))
            {
                if (false == CheckDirectory(strLogFilePath))
                {
                    throw new ApplicationException("problems with log file path");
                }
                FileStream fs = new FileStream(strLogFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                fs.Close();
            }
            Exception    last_exception = null;
            StreamWriter sw             = null;

            for (int timeout = 0; timeout < 30; timeout++)
            {
                try
                {
                    sw = new StreamWriter(strLogFilePath, true);
                    if (sw != null)
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    last_exception = ex;
                    sw             = null;
                }
                Thread.Sleep(100);
            }
            if (sw == null)
            {
                // MessageBox.Show("can't open log file: " + last_exception.Message);
                throw new Exception("can't open log file: " + last_exception.Message);
            }


            StringBuilder line = new StringBuilder();

            line.Append(DateTime.Now.ToString("u"));
            line.Append(" ");
            line.Append(m_source);
            line.Append(" ");
            line.Append(level.ToString());
            line.Append(" ");
            line.Append(message);
            if (code != 0)
            {
                line.Append(" (code=");
                line.Append(code.ToString());
                line.Append(")");
            }

            sw.WriteLine(line.ToString());

            sw.Flush();
            sw.Close();
        }
Пример #44
0
        protected void Log(LoggerLevel loggerLevel, string loggerName, string message, Exception exception)
        {
            TextWriter output = Console.Out;
            if (loggerLevel == LoggerLevel.Error || loggerLevel == LoggerLevel.Fatal)
                output = Console.Error;

            output.WriteLine("[{0}] '{1}' {2}", loggerLevel, loggerName, message);
            if (exception != null)
            {
                output.WriteLine("[{0}] '{1}' {2}: {3} {4}", new object[] { loggerLevel.ToString(), loggerName, exception.GetType().FullName, exception.Message, exception.StackTrace });
            }
        }
Пример #45
0
		protected override void Log(LoggerLevel loggerLevel, String loggerName, String message, Exception exception)
		{
			if (writer == null) return; // just in case it's been disposed

			writer.WriteLine("[{0}] '{1}' {2}", loggerLevel.ToString(), loggerName, message);

			if (exception != null)
			{
				writer.WriteLine("[{0}] '{1}' {2}: {3} {4}",
				                 loggerLevel.ToString(),
				                 loggerName,
				                 exception.GetType().FullName,
				                 exception.Message,
				                 exception.StackTrace);
			}
		}