Beispiel #1
0
 public LogMessage(string msg)
 {
     this.level = LogLevels.Verbose;
     this.msgText = msg;
     this.subject = "unknown";
     this.created = DateTime.Now;
 }
Beispiel #2
0
 public static void LogFile(string entry, LogLevels level)
 {
     if (Silent)
     {
         return;
     }
     if (CurrentLevel > (byte)level)
     {
         return;
     }
     entry = DateTime.Now.TimeOfDay.ToString() + " " + Convert.ToString(Thread.CurrentThread.ManagedThreadId) + " " + entry;
     Queue.Synchronized(logEntriesList).Enqueue(entry);
     Monitor.Enter(logThread);
     if(!logThread.IsAlive)
     {
         logThread.Start();
     }
     Monitor.Exit(logThread);
     try
     {
         sm.Release();
     }
     catch
     {
     }
 }
Beispiel #3
0
 public void Log(LogLevels logLevel, string str)
 {
     using (var sw = GetStreamWriter())
     {
         sw.WriteLine("{0}:{1:HH-mm-ss}: {2}", logLevel, DateTime.Now, str);
     }
 }
 public static void LogWithTags(this ExceptionlessClient client, string logMessage, string[] tags, string source = null, LogLevels level = LogLevels.Info)
 {
     if (client.LoggingEnabled())
         client.CreateLog(source, logMessage, level.Text())
             .AddTags(tags)
             .Submit();
 }
Beispiel #5
0
 public LogMessage(LogLevels type, string msg)
 {
     this.level = type;
     this.msgText = msg;
     this.subject = "unknown";
     this.created = DateTime.Now;
 }
Beispiel #6
0
        public static void VisualLog(LogLevels loglevel, string type, String ex)
        {
            // create output to console
            TextWriterTraceListener console = new TextWriterTraceListener();
            console.Writer = Console.Out;
            Trace.Listeners.Add(console);
            //output error
            if (System.Diagnostics.Trace.Listeners.Count > 0)
            {
                Trace.Write(new TraceData(loglevel, DateTime.Now, type, ex));
            }
            //close streams
            console.Close();

            if (!ApplicationType.GetApplicationType().Equals(ApplicationType.Type.Console))
            {
                //messagebox
                MessageBoxIcon icon = MessageBoxIcon.None;
                switch (loglevel)
                {
                    case LogLevels.Error:
                        icon = MessageBoxIcon.Error;
                        break;
                    case LogLevels.Warning:
                        icon = MessageBoxIcon.Warning;
                        break;
                    case LogLevels.Info:
                        icon = MessageBoxIcon.Information;
                        break;
                }
                MessageBox.Show(ex, type, MessageBoxButtons.OK, icon);
            }
        }
Beispiel #7
0
        /// <summary>
        /// Writes a message to the log file.
        /// </summary>
        /// <param name="message">The message to write.</param>
        /// <param name="level">The level of severity of the log message.</param>
        public void Write(string message, LogLevels level)
        {
            lock (_lockObject)
            {
                if (_logLevel < level)
                {
                    // This message is more detailed than the user wants logged.
                    return;
                }

                if (string.IsNullOrEmpty(_filename))
                {
                    return;
                }

                using (var file = new StreamWriter(_filename, true))
                {
                    file.WriteLine(
                        string.Concat(
                            DateTime.UtcNow.ToString("M/d/yyyy HH:mm:ss"),
                            " Level ",
                            Enum.GetName(typeof(LogLevels), level),
                            ": ",
                            message));
                }
            }
        }
Beispiel #8
0
        private static void WriteLog(LogLevels level, string message)
        {
            if (!Directory.Exists(LogFolder))
            {
                Directory.CreateDirectory(LogFolder);
            }

            if (level >= Settings.settingsStore.logLevel)
            {
                string output;
                if (Settings.settingsStore.useUTCTimeInLog)
                {
                    output = "[" + DateTime.UtcNow.ToString("HH:mm:ss") + "][" + level.ToString() + "] : " + message;
                }
                else
                {
                    output = "[" + DateTime.Now.ToString("HH:mm:ss") + "][" + level.ToString() + "] : " + message;
                }
                Console.WriteLine(output);
                ClientHandler.SendConsoleMessageToAdmins(output);
                try
                {
                    lock (logLock) {
                        File.AppendAllText(LogFilename, output + Environment.NewLine);
                    }
                }
                catch (Exception e)
                {
                    Console.ForegroundColor = ConsoleColor.DarkRed;
                    Console.WriteLine("Error writing to log file!, Exception: " + e);
                    Console.ForegroundColor = ConsoleColor.Gray;
                }
            }
        }
Beispiel #9
0
        protected override void WriteLog(LogLevels logLevel, string logRecord)
        {
            if (!Preferences.AutoLog) return;
            
            // 20140317
            // turning off the logger
//            switch (logLevel) {
//                case LogLevels.Fatal:
//                    Logger.Fatal(logRecord);
//                    break;
//                case LogLevels.Error:
//                    Logger.Error(logRecord);
//                    break;
//                case LogLevels.Warn:
//                    Logger.Warn(logRecord);
//                    break;
//                case LogLevels.Info:
//                    Logger.Info(logRecord);
//                    break;
//                case LogLevels.Debug:
//                    Logger.Debug(logRecord);
//                    break;
//                case LogLevels.Trace:
//                    Logger.Trace(logRecord);
//                    break;
//            }
        }
        public static void Log(LogLevels level, string text)
        {
#if LOG
            if (!File.Exists(LogPath))
            {
                File.WriteAllText(LogPath, "Executable: " + Application.ExecutablePath + "\r\n" +
                    "Version: " + Application.ProductVersion + "\r\n" +
                    "Installed .Net Framework: " + typeof(object).Assembly.GetName().Version.ToString() + "\r\n" +
                    "OS: " + Environment.OSVersion.VersionString + "\r\n", Encoding.UTF8);
            }
            switch (level)
            {
                case LogLevels.Warning:
                    text = "[WARN] " + text;
                    break;
                case LogLevels.Error:
                    text = "[ERRO] " + text;
                    break;
                case LogLevels.Information:
                default:
                    text = "[INFO] " + text;
                    break;
            }
            File.AppendAllLines(LogPath, new string[] { text }, Encoding.UTF8);
#endif
        }
Beispiel #11
0
 public void AppendEntry(string sourceDomainName, global::System.Reflection.AssemblyName sourceAssembly, string sourceTypeName, string sourceMethodName, LogLevels level, DateTime timestamp, string message)
 {
     _logController.AppendEntry(sourceDomainName, sourceAssembly, sourceTypeName, sourceMethodName, level, timestamp, message);
     System.sDomain[] doms = System.Domains;
     foreach (System.sDomain dom in doms)
         dom.Core.AppendEntry(sourceDomainName, sourceAssembly, sourceTypeName, sourceMethodName, level, timestamp, message);
 }
Beispiel #12
0
		/// <summary>
		/// To record a message to the log.
		/// </summary>
		/// <param name="receiver">Logs receiver.</param>
		/// <param name="level">The level of the log message.</param>
		/// <param name="getMessage">The function returns the text for <see cref="LogMessage.Message"/>.</param>
		public static void AddLog(this ILogReceiver receiver, LogLevels level, Func<string> getMessage)
		{
			if (receiver == null)
				throw new ArgumentNullException(nameof(receiver));

			receiver.AddLog(new LogMessage(receiver, receiver.CurrentTime, level, getMessage));
		}
Beispiel #13
0
 private static void LogLine(LogLevels level, string message)
 {
     if ((Level & level) == level)
     {
         LogStream.WriteLine(message);
     }
 }
		public void WriteText(System.IO.TextWriter writer, LogLevels level, DateTime dateTime, string text)
		{
			string sLevel;
			switch (level)
			{
				case LogLevels.Info:
				default:
					sLevel = "I";
					break;

				case LogLevels.Diagnostic:
					sLevel = "D";
					break;

				case LogLevels.Warning:
					sLevel = "W";
					break;

				case LogLevels.Error:
					sLevel = "E";
					break;
			}

			writer.WriteLine("{0}:{1} {2} [{4}]: {3}",
				sLevel, dateTime.ToShortDateString(), dateTime.ToLongTimeString(),
				text, Thread.CurrentThread.GetHashCode());
		}
Beispiel #15
0
        /// <summary>
        /// Static function used to log textual information to the console output.
        /// </summary>
        /// <param name="it"></param>
        /// <param name="text"></param>
        /// <param name="level"></param>
        internal static void Write(object it, string text, LogLevels level)
        {
            string label = "";

            if (level > Level)
                return;

            switch (level)
            {
                case LogLevels.Debug:
                    label = "[DEBUG] ";
                    break;

                case LogLevels.Error:
                    label = "[ERROR] ";
                    break;

                case LogLevels.Info:
                    break;

                case LogLevels.Warning:
                    label = "[WARNING] ";
                    break;
            }

            if (it == null)
                Console.WriteLine(label + text);
            else
                Console.WriteLine(it.GetType().Name + ": " + label + text);
        }
Beispiel #16
0
 /// <summary>
 /// Logs a message to the database logger.
 /// If logger not defined, logs to the console.
 /// </summary>
 public static void AltLog(LogLevels eventType, int id, string message, bool forceconsole = false)
 {
     if (!forceconsole && Logger != null)
         Logger.TraceEvent(eventType, id, message);
     else
         Console.WriteLine(eventType.ToString() + " " + id + " " + LMLoggers.LognLM.FlattenChars(message));
 }
Beispiel #17
0
 public LogMessage(LogLevels type, string msg, string subject)
 {
     this.level = type;
     this.msgText = msg;
     this.subject = subject;
     this.created = DateTime.Now;
 }
		/// <summary>
		/// Logs a message.
		/// </summary>
		/// <param name="level">Log level of the message.</param>
		/// <param name="sMsg">Message to log.</param>
		public void Log(LogLevels level, string sMsg, params Object[] args)
		{
			LogRecord record = new LogRecord(level, sMsg, args);
			lock(this)
			{
				_records.Enqueue(record);
			}
		}
Beispiel #19
0
 protected void WriteLog(LogLevels logLevel, ErrorRecord errorRecord)
 {
     //if (Preferences.AutoLog) {
         
     WriteLog(logLevel, errorRecord.Exception.Message);
     WriteLog(logLevel, "Script: '" + errorRecord.InvocationInfo.ScriptName + "', line: " + errorRecord.InvocationInfo.Line.ToString());
     //}
 }
		/// <summary>
		/// Log the message to each of the logs in the list.
		/// </summary>
		/// <param name="level">Level of the message.</param>
		/// <param name="sMsg">Message to send.</param>
		public virtual void Log(LogLevels level, string sMsg, params Object[] args)
		{
			// Send the message to each log
			foreach(ILog log in _logs)
			{
				log.Log(level, sMsg, args);
			}
		}
Beispiel #21
0
		public void Log(DateTime date, LogLevels level, Dictionary<string, object> data, string sFormat, params object[] args)
		{
			// Send the message to each log
			foreach (ILog log in _logs)
			{
				log.Log(date, level, data, sFormat, args);
			}
		}
Beispiel #22
0
        public LoggerConfig(string applicationName, LogLevels logLevel)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new ArgumentNullException(nameof(applicationName));

            ApplicationName = applicationName;
            LogLevel = logLevel;
        }
Beispiel #23
0
 private static void LogMessage(LogLevels level, string message)
 {
     if (_writer != null)
     {
         if ((int)_writer.LogLevel >= (int)level)
             _writer.WriteLogMessage(DateTime.Now, level, message);
     }
 }
Beispiel #24
0
 protected void WriteLog(LogLevels logLevel, System.Management.Automation.ErrorRecord errorRecord)
 {
     if (Preferences.AutoLog) {
         
         this.WriteLog(logLevel, errorRecord.Exception.Message);
         this.WriteLog(logLevel, "Script: '" + errorRecord.InvocationInfo.ScriptName + "', line: " + errorRecord.InvocationInfo.Line.ToString());
     }
 }
Beispiel #25
0
 private void DispatchToLoggers(LogLevels logLevel, Action<ILogger> dispatchAction)
 {
     foreach (var logDispatcher in loggers)
     {
         if ((logDispatcher.LogLevel & logLevel) == logLevel)
         {
             dispatchAction(logDispatcher);
         }
     }
 }
Beispiel #26
0
 public void Write(LogLevels level, string msg)
 {
     if(_level <= level)
       lock (_fileLock)
       {
           System.IO.File.AppendAllText(_file, string.Format("[{0}] [{1}] {2} \n", DateTime.Now, level, msg));
           if(OnLog != null)
             OnLog(level, msg);
       }
 }
Beispiel #27
0
        public void Emit(LogChannel source, LogLevels level, string tag, string message, object[] args)
        {
            if (paused)
                return;

            LastSource  = source;
            LastLevel   = level;
            LastTag     = tag;
            LastMessage = message;
            LastArgs    = args;
        }
Beispiel #28
0
 public LogEntry(LogLevels level, string message) {
     this.timestamp = DateTime.UtcNow;
     this.level = level;
     this.message = message;
     try {
         //this.username = Strata.Context.User.Username;
         this.username = "******";
     } catch {
         this.username = "******";
     }
 }
Beispiel #29
0
        public static void Write(LogLevels level, string message)
        {
            if (level <= LogLevel)
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(LogFileName, true);

                file.WriteLine(string.Format("[{0:yyyy.MM.dd HH:mm:ss}] {1} - {2}", DateTime.Now, level, message));

                file.Close();
            }
        }
 public SerilogRollingFileConfiguration(
     string path,
     long? fileSize = null,
     int? filesToKeep = null,
     LogLevels logLevel = LogLevels.Debug)
     : this()
 {
     FilePath = path;
     FileSize = fileSize;
     NumberOfFilesToKeep = filesToKeep;
     LogLevel = logLevel;
 }
Beispiel #31
0
        public void ConfigureServices(IServiceCollection services)
        {
            // 注入配置文件
            services.AddSingleton(Configuration as IConfigurationRoot);

            #region 日志配置
            LogLevels logLevel    = LogLevels.Info;
            int       maxDays     = 7;
            var       logConfig   = Configuration.GetSection("Log");
            string    maxFileSize = "10MB";
            if (logConfig != null)
            {
                Enum.TryParse(logConfig["Level"] ?? "", out logLevel);
                int.TryParse(logConfig["SaveDays"], out maxDays);
                maxFileSize = logConfig["MaxFileSize"];
                if (string.IsNullOrEmpty(maxFileSize))
                {
                    maxFileSize = "10MB";
                }
            }
            string logFolder = Path.Combine(AppContext.BaseDirectory, "Logs");
            LoggerManager.InitLogger(new LogConfig()
            {
                LogBaseDir         = logFolder,
                MaxFileSize        = maxFileSize,
                LogLevels          = logLevel,
                IsAsync            = true,
                LogFileTemplate    = LogFileTemplates.PerDayDirAndLogger,
                LogContentTemplate = LogLayoutTemplates.SimpleLayout,
            });
            LoggerManager.SetLoggerAboveLevels(logLevel);
            LoggerManager.StartClear(maxDays, logFolder, LoggerManager.GetLogger("clear"));

            #endregion

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            // 注入SignalR
            services.AddSignalR();
            services.AddDbContext <PointsGameDbContext>(it =>
            {
                it.UseMySql(Configuration["Data:DefaultConnection:ConnectionString"]);
            });
            services.AddScoped <ApiCore.ITransaction <PointsGameDbContext>, ApiCore.Stores.Transaction <PointsGameDbContext> >();
            #region 认证中心接口访问权限配置
            string authUrl      = Configuration["AuthUrl"];
            string clientId     = Configuration["ClientID"];
            string clientSecret = Configuration["ClientSecret"];
            string appName      = Configuration["AppName"];

            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";

                options.Authority = authUrl;
                //options.Audiences.Add("*");
                options.ClientId             = clientId;
                options.ClientSecret         = clientSecret;
                options.RequireHttpsMetadata = false;

                options.ResponseType = "code";
                options.SaveTokens   = true;
                options.GetClaimsFromUserInfoEndpoint = true;
                options.Scope.Remove("profile");
                options.Scope.Add("openid");
                options.Scope.Add("AuthenticationService");

                options.Scope.Add(appName);

                options.Scope.Add("offline_access");
                // 认证错误时捕获错误信息
                options.Events = new Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        return(Task.CompletedTask);
                    }
                };
            })
            .AddJwtBearer(OAuthValidationDefaults.AuthenticationScheme, options =>
            {
                options.Authority            = authUrl;
                options.RequireHttpsMetadata = false;
                options.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents
                {
                    OnAuthenticationFailed = (context) =>
                    {
                        var msg = context.Exception;

                        return(Task.CompletedTask);
                    }
                };
                //注册应用的AppName值
                options.Audience = appName;
            });
            #endregion

            services.AddUserDefined();
            // 注入认证中心
            services.AddAuthenticationDefined(options =>
            {
                options.AuthenticationUrl = authUrl;//必填
            });
            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "积分系统接口文档",
                    TermsOfService = "None",
                });
                c.IgnoreObsoleteActions();
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "PointsGame.xml");
                c.IncludeXmlComments(xmlPath);
                // 添加httpHeader参数
                c.OperationFilter <HttpHeaderOperation>();
            });
        }
Beispiel #32
0
 /// <summary>
 /// Log specified level log entry
 /// </summary>
 /// <param name="level">Log level of log entry</param>
 /// <param name="formatedMessage">Formated string for logged description</param>
 /// <param name="args">An object array that contains zero or more objects to format</param>
 public void Write(LogLevels level, string formatedMessage, params object[] args)
 {
     Entry(new LogEntry(level, String.Format(formatedMessage, args), null, null));
 }
        protected override void writeLog(LogLevels level, string tag, string message, System.Exception e)
        {
            string output = String.Format("[{0}]:[{1}] - {2} - {3}", level, tag, message, null == e ? "" : e.StackTrace);

            Console.WriteLine(output);
        }
Beispiel #34
0
 /// <summary>
 /// This method constructs a new log entry.
 /// Each instance of a log entry stores information about the log including the date, time, LogLevel, and the message.
 /// </summary>
 /// <param name="Message">String: The main message of the log.</param>
 /// <param name="Severity">LogLevels: The severity of this log. The default is "Information".</param>
 public LogItem(string Message, LogLevels Severity = LogLevels.Information)
 {
     this.Message = Message;
     Level        = Severity;
 }
 public ConsoleDestination(LogLevels level = LogLevels.Debug) : base(level)
 {
 }
Beispiel #36
0
 /// <summary>
 /// Set minimal output level for logged messages
 /// </summary>
 /// <param name="minLevel">Minimal level for logged messages</param>
 public void SetOutputLevel(LogLevels minLevel)
 {
     _minLevel = minLevel;
 }
 protected override void LogStatement(string message, LogLevels level)
 {
     LoggingEvent.Invoke(this, new LoggerArgs {
         LogLevel = level, Message = message
     });
 }
Beispiel #38
0
 public static void setLoggingLevel(LogLevels ThisLogLevel)
 {
     LogLevel = ThisLogLevel;
 }
Beispiel #39
0
 public void Log(string message, LogLevels level, [CallerMemberName] string methodName = "")
 {
     return;
 }
Beispiel #40
0
 public void LogLine(string elementID, AssemblyName assembly, string fileName, int lineNumber, LogLevels level, DateTime timestamp, string message)
 {
     AppendValue(string.Format("{0}|{1}|{2}|{3}[{4}]|Element[{5}]|{6}\r\n", new object[]
     {
         timestamp.ToString(Constants.DATETIME_FORMAT),
         level,
         assembly.Name,
         fileName,
         lineNumber,
         elementID,
         message
     }));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="EmulationSettings"/>.
 /// </summary>
 public EmulationSettings()
 {
     MarketTimeChangedInterval = TimeSpan.FromMinutes(1);
     LogLevel = LogLevels.Info;
 }
 public FileLogger(LogLevels levels, string file)
 {
     this.FileName = file ?? throw new ArgumentNullException(nameof(file));
     this.Levels   = levels;
 }
Beispiel #43
0
 /// <summary>
 /// Determines if a log level is to low
 /// </summary>
 /// <param name="logLevel"></param>
 /// <returns></returns>
 public bool IsLoggingDisabled(LogLevels logLevel)
 {
     return(CurrentLogLevel > logLevel);
 }
Beispiel #44
0
 /// <summary>
 /// Determines if a log level is high enough
 /// </summary>
 /// <param name="logLevel"></param>
 /// <returns></returns>
 public bool IsLoggingEnabled(LogLevels logLevel)
 {
     return(CurrentLogLevel <= logLevel);
 }
 protected void Log(string text, LogLevels level = LogLevels.DEBUG)
 {
     Logger.Log("[OUTPUTS] " + text, level);
 }
Beispiel #46
0
 public void Log(LogLevels level, string message)
 {
     ExecuteApplication("log", level.ToString().ToUpper() + " " + message, false);
 }
 protected void LogFormat(LogLevels level, string text, params object[] args)
 {
     Logger.LogFormat(level, "[OUTPUTS] " + text, args);
 }
 protected LoggingDestination(LogLevels reportingLevel)
 {
     _reportingLevel = reportingLevel;
 }
 public EventLogDestination(LogLevels logLevel) : this(null, logLevel)
 {
 }
        protected override void LogStatement(string message, LogLevels level)
        {
            var msg = $"{DateTime.Now} :: {level.ToString().PadLeft(12)}:  {message}";

            LogStatement(msg);
        }
 public UserInterfaceDestination(LogLevels reportingLevel) : base(reportingLevel)
 {
 }
Beispiel #52
0
 /// <summary>
 /// Logs an information message
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="logLevel"></param>
 public static void LogInfo(string msg, LogLevels logLevel = LogLevels.Information)
 {
     Log(msg, logLevel: logLevel);
 }
 protected void Log(string text, LogLevels level = LogLevels.DEBUG)
 {
     Logger.Log("[FEEDER] " + text, level);
 }
Beispiel #54
0
        public void PopulateEvent(Event ev)
        {
            if (MinDate.HasValue || MaxDate.HasValue)
            {
                ev.Date = RandomData.GetDateTime(MinDate ?? DateTime.MinValue, MaxDate ?? DateTime.MaxValue);
            }

            ev.Type = EventTypes.Random();
            if (ev.Type == Event.KnownTypes.FeatureUsage)
            {
                ev.Source = FeatureNames.Random();
            }
            else if (ev.Type == Event.KnownTypes.NotFound)
            {
                ev.Source = PageNames.Random();
            }
            else if (ev.Type == Event.KnownTypes.Log)
            {
                ev.Source  = LogSources.Random();
                ev.Message = RandomData.GetString();

                string level = LogLevels.Random();
                if (!String.IsNullOrEmpty(level))
                {
                    ev.Data[Event.KnownDataKeys.Level] = level;
                }
            }

            if (RandomData.GetBool(80))
            {
                ev.Geo = RandomData.GetCoordinate();
            }

            if (RandomData.GetBool(20))
            {
                ev.Value = RandomData.GetDecimal();
            }

            ev.SetUserIdentity(Identities.Random());
            ev.SetVersion(RandomData.GetVersion("2.0", "4.0"));

            ev.AddRequestInfo(new RequestInfo {
                //ClientIpAddress = ClientIpAddresses.Random(),
                Path = PageNames.Random()
            });

            ev.Data.Add(Event.KnownDataKeys.EnvironmentInfo, new EnvironmentInfo {
                IpAddress   = MachineIpAddresses.Random() + ", " + MachineIpAddresses.Random(),
                MachineName = MachineNames.Random()
            });

            for (int i = 0; i < RandomData.GetInt(1, 3); i++)
            {
                string key = RandomData.GetWord();
                while (ev.Data.ContainsKey(key) || key == Event.KnownDataKeys.Error)
                {
                    key = RandomData.GetWord();
                }

                ev.Data.Add(key, RandomData.GetString());
            }

            int tagCount = RandomData.GetInt(1, 3);

            for (int i = 0; i < tagCount; i++)
            {
                string tag = EventTags.Random();
                if (!ev.Tags.Contains(tag))
                {
                    ev.Tags.Add(tag);
                }
            }

            if (ev.Type == Event.KnownTypes.Error)
            {
                if (RandomData.GetBool())
                {
                    // limit error variation so that stacking will occur
                    if (_randomErrors == null)
                    {
                        _randomErrors = new List <Error>(Enumerable.Range(1, 25).Select(i => GenerateError()));
                    }

                    ev.Data[Event.KnownDataKeys.Error] = _randomErrors.Random();
                }
                else
                {
                    // limit error variation so that stacking will occur
                    if (_randomSimpleErrors == null)
                    {
                        _randomSimpleErrors = new List <SimpleError>(Enumerable.Range(1, 25).Select(i => GenerateSimpleError()));
                    }

                    ev.Data[Event.KnownDataKeys.SimpleError] = _randomSimpleErrors.Random();
                }
            }
        }
Beispiel #55
0
 /// <summary>
 /// Logs exceptions in the applications
 /// </summary>
 /// <param name="ex"></param>
 public static void Log(Exception ex, LogLevels logLevel = LogLevels.Error)
 {
     Log(ex.GetBaseException().Message, ex, logLevel: logLevel);
 }
 protected abstract void LogStatement(string message, LogLevels level);
Beispiel #57
0
        /// <summary>
        /// Logs messages to the standard log output for Markdown Monster:
        ///
        /// * Application Insights
        /// * Local Log File
        ///
        /// </summary>
        /// <param name="msg"></param>
        public static void Log(string msg, Exception ex = null, bool unhandledException = false, LogLevels logLevel = LogLevels.Error)
        {
            string version    = GetVersion();
            string winVersion = null;

            if (Telemetry.UseApplicationInsights)
            {
                var secs = (int)DateTimeOffset.UtcNow.Subtract(AppRunTelemetry.Telemetry.Timestamp).TotalSeconds;

                if (ex != null)
                {
                    AppRunTelemetry.Telemetry.Success = false;
                    AppInsights.TrackException(ex,
                                               new Dictionary <string, string>
                    {
                        { "msg", msg },
                        { "exmsg", ex.Message },
                        { "exsource", ex.Source },
                        { "extrace", ex.StackTrace },
                        { "severity", unhandledException ? "unhandled" : "" },
                        { "version", version },
                        { "winversion", winVersion },
                        { "dotnetversion", MarkdownMonster.Utilities.mmWindowsUtils.GetDotnetVersion() },
                        { "usage", Configuration.ApplicationUpdates.AccessCount.ToString() },
                        { "registered", UnlockKey.IsRegistered().ToString() },
                        { "culture", CultureInfo.CurrentCulture.IetfLanguageTag },
                        { "uiculture", CultureInfo.CurrentUICulture.IetfLanguageTag },
                        { "seconds", secs.ToString() },
                        { "level", ((int)logLevel).ToString() + " - " + logLevel.ToString() }
                    });
                }
                else
                {
                    // message only
                    var props = new Dictionary <string, string>()
                    {
                        { "msg", msg },
                        { "usage", Configuration.ApplicationUpdates.AccessCount.ToString() },
                        { "registered", UnlockKey.IsRegistered().ToString() },
                        { "version", GetVersion() },
                        { "culture", CultureInfo.CurrentCulture.IetfLanguageTag },
                        { "uiculture", CultureInfo.CurrentUICulture.IetfLanguageTag },
                        { "seconds", secs.ToString() },
                        { "level", ((int)logLevel).ToString() + " - " + logLevel.ToString() }
                    };
                    AppInsights.TrackTrace(msg, props);
                }
            }

            // also log to the local error log
            LogLocal(msg, ex);
        }
Beispiel #58
0
 /// <summary>
 /// Writes a trace message
 /// </summary>
 /// <param name="msg"></param>
 public static void LogTrace(string msg, LogLevels logLevel = LogLevels.Trace)
 {
     Log(msg, logLevel: logLevel);
 }
Beispiel #59
0
 public void SetSessionLogLevel(LogLevels level)
 {
     ExecuteApplication("session_loglevel", level.ToString().ToLower(), true);
 }
 protected TextLogger(LogLevels reportingLevel) : base(reportingLevel)
 {
 }