static IConfiguration Configure()
        {
            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new Dictionary <string, string> {
                { "MongoUrl", "mongodb://localhost:27017" },
                { "MongoDatabase", "stockmarket" },
                { "QueueHost", "localhost" },
                { "QueueName", "stockmarket" },
                { "RedisHost", "localhost" },
                { "LogLevel", LogEventLevel.Information.ToString() },
            })
                         .AddEnvironmentVariables()
                         .Build();

            var logLevel = LogEventLevel.Warning;

            Enum.TryParse(config["LogLevel"], out logLevel);

            var logLevelSwitch = new Serilog.Core.LoggingLevelSwitch(logLevel);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.ControlledBy(logLevelSwitch)
                         .WriteTo.LiterateConsole()
                         .CreateLogger();

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Formatting       = Formatting.None,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            return(config);
        }
Beispiel #2
0
        public void LogInformation(LogLevels eventLevel, string information, Exception exInfo = null, params object[] values)
        {
            ValidateMandatoryEntries(connectionStringLogginDb, customLoggingLevel, loggingTable);

            var columnOptions = GetColumnOptions();


            Serilog.Debugging.SelfLog.Enable(msg => System.Diagnostics.Debug.WriteLine(msg));

            var levelSwitch = new Serilog.Core.LoggingLevelSwitch();

            levelSwitch.MinimumLevel = getLogEventLevel(customLoggingLevel);
            var logLevel = getLogEventLevel(eventLevel.ToString());

            using (var log = GetLog(connectionStringLogginDb, loggingTable, columnOptions, levelSwitch))
            {
                if (log.IsEnabled(logLevel))
                {
                    if (exInfo != null)
                    {
                        log.Write(logLevel, exInfo, information, values);
                    }
                    else
                    {
                        log.Write(logLevel, information, values);
                    }
                }
                else
                {
                    var result = $"Logger: eventLevel:{nameof(logLevel)} is not enabled";
                    System.Diagnostics.Debug.WriteLine(result);
                }
            }
        }
Beispiel #3
0
        private static void InitLogger(bool verbose)
        {
            var minLevel          = verbose ? Serilog.Events.LogEventLevel.Verbose : Serilog.Events.LogEventLevel.Information;
            var minLogLevelSwitch = new Serilog.Core.LoggingLevelSwitch(minLevel);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.ControlledBy(minLogLevelSwitch)
                         .WriteTo.Console()
                         .CreateLogger();
        }
Beispiel #4
0
        public static async Task <int> Main(string[] args)
        {
            var minLogLevelSwitch = new Serilog.Core.LoggingLevelSwitch();

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.ControlledBy(minLogLevelSwitch)
                         .WriteTo.Console()
                         .CreateLogger();

            try
            {
                var helpWriter = new StringWriter();

                var commandLineParser = new Parser(s =>
                {
                    s.HelpWriter                = helpWriter;
                    s.CaseSensitive             = false;
                    s.CaseInsensitiveEnumValues = true;
                });

                var result = await commandLineParser
                             .ParseArguments <
                    CosmosBackupOptions,
                    CosmosRestoreOptions,
                    CosmosFeedOptions,
                    MartenBackupOptions,
                    MartenRestoreOptions
                    >(args)
                             .WithParsed((ICommonOptions o) =>
                {
                    minLogLevelSwitch.MinimumLevel = o.Verbosity;
                    Log.Verbose("Started with arguments {Arguments}", args);
                    Log.Verbose("The parsed options are {@Parsed}", o);
                })
                             .MapResult(
                    (CosmosBackupOptions opts) => new CosmosBackupOperation(opts).ExecuteAsync(),
                    (CosmosRestoreOptions opts) => new CosmosRestoreOperation(opts).ExecuteAsync(),
                    (CosmosFeedOptions opts) => new CosmosFeedOperation(opts).ExecuteAsync(),
                    (MartenBackupOptions opts) => new MartenBackupOperation(opts).ExecuteAsync(),
                    (MartenRestoreOptions opts) => new MartenRestoreOperation(opts).ExecuteAsync(),
                    errs =>
                {
                    Console.WriteLine(helpWriter.ToString());
                    return(Task.FromResult(false));
                }).ConfigureAwait(false);

                return(result ? 0 : 1);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Unexpected error: {Message}", ex.Message);
                return(-1);
            }
        }
Beispiel #5
0
        private void InitLogging(Shared.ServiceConfig serverConfig)
        {
            _loggingLevelSwitch = new Serilog.Core.LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);

            SetLoggingLevel(serverConfig?.LogLevel);

            _serviceLog = new Loggy(
                new LoggerConfiguration()
                .MinimumLevel.ControlledBy(_loggingLevelSwitch)
                .WriteTo.Debug()
                .WriteTo.File(Path.Combine(Util.GetAppDataFolder("logs"), "session.log"), shared: true, flushToDiskInterval: new TimeSpan(0, 0, 10), rollOnFileSizeLimit: true, fileSizeLimitBytes: 5 * 1024 * 1024)
                .CreateLogger()
                );

            _serviceLog?.Information($"Logging started: {_loggingLevelSwitch.MinimumLevel}");
        }
Beispiel #6
0
        private void ThisAddInStartup(object sender, EventArgs e)
        {
            try
            {
                var loggingKeyDown = false;
                var currentDomain  = AppDomain.CurrentDomain;
                currentDomain.AssemblyResolve    += currentDomain_AssemblyResolve;
                currentDomain.UnhandledException += CurrentDomain_UnhandledException;

                var levelSwitch = new Serilog.Core.LoggingLevelSwitch(Serilog.Events.LogEventLevel.Error);
                var config      = new LoggerConfiguration()
                                  .ReadFrom.AppSettings()
                                  .MinimumLevel.ControlledBy(levelSwitch);;

                if (System.Windows.Input.Keyboard.IsKeyDown(Constants.LoggingHotKey1) ||
                    System.Windows.Input.Keyboard.IsKeyDown(Constants.LoggingHotKey2))
                {
                    loggingKeyDown   = true;
                    _debugLogEnabled = true;

                    // increase the default log level when the logging hot key is held down
                    levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;
                    Log.Debug("Debug Logging Enabled");

                    // force logging to rolling log file (in case the app settings has switched this off)
                    var logPath = Path.Combine(ApplicationPaths.LogPath
                                               , Constants.ExcelLogFileName);
                    config.WriteTo.File(logPath, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Debug, retainedFileCountLimit: 10);
                }
                log        = config.CreateLogger();
                Log.Logger = log;
                Log.Information("============ Excel Add-in Startup =============");
                ExcelInfo.WriteToLog(this);
                if (loggingKeyDown)
                {
                    if (_ribbon != null)
                    {
                        _ribbon.DebugLoggingEnabled = true;
                    }
                    Log.Information($"Logging enabled by {Constants.LoggingHotKeyName} Key at startup");
                }
                CreateRibbonObjects();
            } catch (Exception ex)
            {
                CrashReporter.ReportCrash(ex, "DAX Studio Excel Addin fatal startup exception");
            }
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .AddInMemoryCollection(new Dictionary <string, string>
            {
                { "QueueHostName", "localhost" },
                { "LogLevel", LogEventLevel.Information.ToString() }
            })
                         .AddEnvironmentVariables()
                         .Build();

            var logLevel = LogEventLevel.Warning;

            Enum.TryParse(config["LogLevel"], out logLevel);

            var logLevelSwitch = new Serilog.Core.LoggingLevelSwitch(logLevel);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.ControlledBy(logLevelSwitch)
                         .WriteTo.LiterateConsole()
                         .CreateLogger();

            var traderId = Guid.NewGuid().ToString("n").Substring(0, 8);

            Log.Information("Starting Trade Bot {traderId}...", traderId);

            var queueHost = config["QueueHost"];

            Log.Verbose("Connecting to message host {queueHost}...", queueHost);

            using (var connection = MessageQueueFactory.Connect(queueHost))
                using (var channel = connection.CreateModel())
                {
                    var queue  = MessageQueueFactory.CreateMessageQueue(channel, config["QueueName"]);
                    var trader = new TradeGenerator(traderId);

                    while (true)
                    {
                        var trade = trader.GenerateTrade();

                        queue.Publish(trade.Type.ToString().ToLower(), trade);

                        Thread.Sleep(1000);
                    }
                }
        }
        public void Initialize()
        {
            Serilog.Debugging.SelfLog.Enable(msg => System.Diagnostics.Debug.WriteLine(msg));
            var levelSwitch = new Serilog.Core.LoggingLevelSwitch();
            levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Verbose;
            string fileLogTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}|{Level}|{Message}{NewLine}{Exception}";
            if (System.Diagnostics.Debugger.IsAttached)
                Log.Logger = new LoggerConfiguration()
                                    .MinimumLevel.ControlledBy(levelSwitch)
                                    .WriteTo.Debug()
                                    .CreateLogger();
            else
                Log.Logger = new LoggerConfiguration()
                                    .MinimumLevel.ControlledBy(levelSwitch)
                                    .WriteTo.File(@"C:\temp\MSHealthAPI.log", outputTemplate: fileLogTemplate, shared: true)
                                    .CreateLogger();

            moClient = new MSHealthAPI.Core.MSHealthClient(MSHEALTH_CLIENT_ID, MSHEALTH_CLIENT_SECRET, MSHEALTH_SCOPE);
            Log.Information(Uri.EscapeUriString(moClient.SignInUri.ToString()));
        }
Beispiel #9
0
        public void LogInformation(LogLevels eventLevel, string information, Exception exInfo = null, params object[] values)
        {
            var connectionStringLogginDb = Configuration.GetSection("ConnectionStrings:LoggingDatabase");
            var customLoggingLevel       = Configuration.GetSection("CustomLoggingLevel");
            var loggingTable             = Configuration.GetSection("LoggingTable");

            ValidateMandatoryEntries(connectionStringLogginDb, customLoggingLevel, loggingTable);

            var columnOptions = GetColumnOptions();

            //Excluding redundant data
            //columnOptions.Properties.ExcludeAdditionalProperties = true;

            //Log in console to trace any Serilog issues
            Serilog.Debugging.SelfLog.Enable(msg => System.Diagnostics.Debug.WriteLine(msg));

            var levelSwitch = new Serilog.Core.LoggingLevelSwitch();

            levelSwitch.MinimumLevel = getLogEventLevel(customLoggingLevel.Value);
            var logLevel = getLogEventLevel(eventLevel.ToString());

            using (var log = GetLog(connectionStringLogginDb.Value, loggingTable.Value, columnOptions, levelSwitch))
            {
                if (log.IsEnabled(logLevel))
                {
                    if (exInfo != null)
                    {
                        log.Write(logLevel, exInfo, information, values);
                    }
                    else
                    {
                        log.Write(logLevel, information, values);
                    }
                }
                else
                {
                    var result = $"Logger: eventLevel:{nameof(logLevel)} is not enabled";
                    System.Diagnostics.Debug.WriteLine(result);
                }
            }
        }
Beispiel #10
0
        public static ILog GetLogger(string managedItemId, Serilog.Core.LoggingLevelSwitch logLevelSwitch)
        {
            if (string.IsNullOrEmpty(managedItemId))
            {
                return(null);
            }

            if (_managedItemLoggers == null)
            {
                _managedItemLoggers = new ConcurrentDictionary <string, Serilog.Core.Logger>();
            }

            Serilog.Core.Logger log = _managedItemLoggers.GetOrAdd(managedItemId, (key) =>
            {
                var logPath = GetLogPath(key);

                try
                {
                    if (System.IO.File.Exists(logPath) && new System.IO.FileInfo(logPath).Length > (1024 * 1024))
                    {
                        System.IO.File.Delete(logPath);
                    }
                }
                catch { }

                log = new LoggerConfiguration()
                      .MinimumLevel.ControlledBy(logLevelSwitch)
                      .WriteTo.Debug()
                      .WriteTo.File(
                    logPath, shared: true,
                    flushToDiskInterval: new TimeSpan(0, 0, 10)
                    )
                      .CreateLogger();

                return(log);
            });

            return(new Loggy(log));
        }
        private static Action <WebHostBuilderContext, LoggerConfiguration> ConfigureLoggin() => (hostingContext, loggerConfiguration) =>
        {
            if (!Enum.TryParse(hostingContext.Configuration["Application:LogLevel"], out LogEventLevel logEventLevel))
            {
                logEventLevel = LogEventLevel.Information;
            }

            var logLevelSwitch = new Serilog.Core.LoggingLevelSwitch(logEventLevel);
            loggerConfiguration
            .MinimumLevel.ControlledBy(logLevelSwitch)
            .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
            .MinimumLevel.Override("Microsoft.ApsNetCore.Hosting.Diagnostics", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .Enrich.WithDemystifiedStackTraces()
            .WriteTo.Console(theme: AnsiConsoleTheme.Code, outputTemplate: "[{Timestamp:yyyy-MM-dd HH.mm.ss.fff zzz} {Level.u3}] [{RequestId}] {Message:lj}{NewLine}{Exception}")
            .WriteTo.Logger(lc =>
            {
                if (!IsLocal)
                {
                    lc.MinimumLevel.ControlledBy(logLevelSwitch)
                    .Enrich.FromLogContext()
                    .Enrich.WithDemystifiedStackTraces()
                    .WriteTo.AmazonCloudWatch(
                        new CloudWatchSinkOptions {
                        LogGroupName = "ProjectChallenge.ItiDigital.Validation", MinimumLogEventLevel = logEventLevel, TextFormatter = new AWSTextFormatter(), LogStreamNameProvider = new LogStremProvider()
                    },
                        new AmazonCloudWatchLogsClient(RegionEndpoint.GetBySystemName(hostingContext.Configuration["CloudWatchRegion"]))
                        );
                }
                else
                {
                    lc
                    .WriteTo.File("log.txt", outputTemplate: "[{Timestamp:yyyy-MM-dd HH.mm.ss.fff zzz} {Level.u3}] [{RequestId}] {Message:lj}{NewLine}{Exception}");
                }
            });
        };
Beispiel #12
0
        public static async Task <int> Main()
        {
            var hostBuilder = new HostBuilder()
                              .ConfigureHostConfiguration(builder =>
            {
                builder.AddEnvironmentVariables();
            })
                              .ConfigureAppConfiguration((ctx, builder) =>
            {
                builder.AddEnvironmentVariables("MAJOR_");
                builder.AddJsonFile("appsettings.json");
                builder.AddJsonFile($"appsettings.{ctx.HostingEnvironment.EnvironmentName}.json", true);

                Debug.WriteLine(ctx.HostingEnvironment.EnvironmentName);

                if (ctx.HostingEnvironment.IsDevelopment())
                {
                    builder.AddUserSecrets <MajorBot>();
                }
            })
                              .ConfigureLogging((ctx, builder) =>
            {
                var logMinimum = new Serilog.Core.LoggingLevelSwitch(ctx.HostingEnvironment.IsDevelopment() ? LogEventLevel.Debug : LogEventLevel.Information);
                var seriLogger = new LoggerConfiguration()
                                 .MinimumLevel.ControlledBy(logMinimum)
                                 .WriteTo.Console()
                                 .WriteTo.RollingFile(@"logs\{date}", restrictedToMinimumLevel: LogEventLevel.Debug)
                                 .CreateLogger();

                builder.AddSerilog(seriLogger);
            })
                              .ConfigureServices((context, services) =>
            {
                services
                .Configure <MajorConfig>(context.Configuration)
                .AddDbContext <MajorContext>(options =>
                {
                    // options.UseSqlite(context.Configuration.GetValue<string>(nameof(MajorConfig.DbConnection)));
                    options.UseNpgsql(context.Configuration.GetConnectionString("MajorDb"));
                })
                .AddSingleton <DiscordSocketClient>()
                .AddSingleton <CommandService>()
                .AddSingleton <CommandHandler>()
                .AddSingleton <InteractiveService>()
                .AddSingleton <ICommandHelpService, CommandHelpService>()

                .AddHostedService <MajorBot>();
            });

            // Ensure disposal at the end of the Main() block
            using IHost built = hostBuilder.Build();

            try
            {
                await built.RunAsync();

                return(0);
            }
            catch (Exception ex)
            {
                Log.ForContext <Program>()
                .Fatal(ex, "Host terminated unexpectedly.");

                if (Debugger.IsAttached && Environment.UserInteractive)
                {
                    Console.WriteLine(Environment.NewLine + "Press any key to exit...");
                    Console.ReadKey(true);
                }

                return(ex.HResult);
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }
Beispiel #13
0
        public static void Main()
        {
            try
            {
                // Setup logging
                var levelSwitch = new Serilog.Core.LoggingLevelSwitch(Serilog.Events.LogEventLevel.Error);
                var config      = new LoggerConfiguration()
                                  .ReadFrom.AppSettings()
                                  .MinimumLevel.ControlledBy(levelSwitch);

                var logPath = Path.Combine(Environment.ExpandEnvironmentVariables(Constants.LogFolder),
                                           Constants.StandaloneLogFileName);

                // if we have a local settings.json file we are running in "portable" mode
                if (JsonSettingProvider.SettingsFileExists())
                {
                    logPath = Path.Combine(JsonSettingProvider.LogPath, Constants.StandaloneLogFileName);
                }


                config.WriteTo.RollingFile(logPath
                                           , retainedFileCountLimit: 10);

                log = config.CreateLogger();

                // need to create application first
                var app = new Application();
                //var app2 = IoC.Get<Application>();

                // add the custom DAX Studio accent color theme
                app.AddDaxStudioAccentColor();


                // load selected theme


                // TODO: Theme - read from settings

                var theme = "Light"; // settingProvider.GetValue<string>("Theme", "Light");
                if (theme == "Dark")
                {
                    app.LoadDarkTheme();
                }
                else
                {
                    app.LoadLightTheme();
                }


                // add unhandled exception handler
                app.DispatcherUnhandledException += App_DispatcherUnhandledException;

                // then load Caliburn Micro bootstrapper
                AppBootstrapper bootstrapper = new AppBootstrapper(Assembly.GetAssembly(typeof(DaxStudioHost)), true);

                _eventAggregator = bootstrapper.GetEventAggregator();
                // read command line arguments
                app.ReadCommandLineArgs();

                // check if user is holding shift key down
                bool isLoggingKeyDown = (System.Windows.Input.Keyboard.IsKeyDown(Constants.LoggingHotKey1) ||
                                         System.Windows.Input.Keyboard.IsKeyDown(Constants.LoggingHotKey2));

                app.Args().LoggingEnabledByHotKey = isLoggingKeyDown;

                var logCmdLineSwitch = app.Args().LoggingEnabled;

                //if (RegistryHelper.IsFileLoggingEnabled() || isLoggingKeyDown || logCmdLineSwitch)
                if (isLoggingKeyDown || logCmdLineSwitch)
                {
#if DEBUG
                    levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Verbose;
                    Log.Debug("Verbose Logging Enabled");
#else
                    levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;
                    Log.Debug("Debug Logging Enabled");
#endif
                }

                //RegistryHelper.IsFileLoggingEnabled();

#if DEBUG
                Serilog.Debugging.SelfLog.Enable(Console.Out);
#endif
                Log.Logger = log;
                Log.Information("============ DaxStudio Startup =============");
                //SsasAssemblyResolver.Instance.BuildAssemblyCache();
                SystemInfo.WriteToLog();
                if (isLoggingKeyDown)
                {
                    log.Information($"Logging enabled due to {Constants.LoggingHotKeyName} key being held down");
                }
                if (logCmdLineSwitch)
                {
                    log.Information("Logging enabled by Excel Add-in");
                }
                Log.Information("Startup Parameters Port: {Port} File: {FileName} LoggingEnabled: {LoggingEnabled}", app.Args().Port, app.Args().FileName, app.Args().LoggingEnabled);

                AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;

                if (app.Args().TriggerCrashTest)
                {
                    throw new ArgumentException("Test Exception triggered by command line argument");
                }

                // force control tooltips to display even if disabled
                ToolTipService.ShowOnDisabledProperty.OverrideMetadata(
                    typeof(Control),
                    new FrameworkPropertyMetadata(true));

                app.Run();
            }
            catch (ArgumentOutOfRangeException argEx)
            {
                var st = new System.Diagnostics.StackTrace(argEx);
                var sf = st.GetFrame(0);
                if (sf.GetMethod().Name == "GetLineByOffset")
                {
                    if (_eventAggregator != null)
                    {
                        _eventAggregator.PublishOnUIThread(new OutputMessage(MessageType.Warning, "Editor syntax highlighting attempted to scan byond the end of the current line"));
                    }
                    log.Warning(argEx, "{class} {method} AvalonEdit TextDocument.GetLineByOffset: {message}", "EntryPoint", "Main", "Argument out of range exception");
                }
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Class: {0} Method: {1} Error: {2} Stack: {3}", "EntryPoint", "Main", ex.Message, ex.StackTrace);
#if DEBUG
                MessageBox.Show(ex.Message, "DAX Studio Standalone unhandled exception");
#else
                // use CrashReporter.Net to send bug to DrDump
                CrashReporter.ReportCrash(ex, "DAX Studio Standalone Fatal crash in Main() method");
#endif
            }
            finally
            {
                Log.Information("============ DaxStudio Shutdown =============");
                Log.CloseAndFlush();
            }
        }
Beispiel #14
0
        public static void Main()
        {
            try
            {
                // Setup logging
                var levelSwitch = new Serilog.Core.LoggingLevelSwitch(Serilog.Events.LogEventLevel.Error);
                var config      = new LoggerConfiguration()
                                  .ReadFrom.AppSettings()
                                  .MinimumLevel.ControlledBy(levelSwitch);

                var logPath = Path.Combine(Environment.ExpandEnvironmentVariables(Constants.LogFolder),
                                           Constants.StandaloneLogFileName);
                config.WriteTo.RollingFile(logPath
                                           , retainedFileCountLimit: 10);

                log = config.CreateLogger();

                // need to create application first
                var app = new Application();

                // add unhandled exception handler
                app.DispatcherUnhandledException += App_DispatcherUnhandledException;

                // then load Caliburn Micro bootstrapper
                AppBootstrapper bootstrapper = new AppBootstrapper(Assembly.GetAssembly(typeof(DaxStudioHost)), true);

                _eventAggregator = bootstrapper.GetEventAggregator();
                // read command line arguments
                app.ReadCommandLineArgs();

                // check if user is holding shift key down
                bool isLoggingKeyDown = (System.Windows.Input.Keyboard.IsKeyDown(Constants.LoggingHotKey1) ||
                                         System.Windows.Input.Keyboard.IsKeyDown(Constants.LoggingHotKey2));

                app.Args().LoggingEnabledByHotKey = isLoggingKeyDown;

                var logCmdLineSwitch = app.Args().LoggingEnabled;


                //if (RegistryHelper.IsFileLoggingEnabled() || isLoggingKeyDown || logCmdLineSwitch)
                if (isLoggingKeyDown || logCmdLineSwitch)
                {
                    levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;
                    Log.Debug("Debug Logging Enabled");
                }

                //RegistryHelper.IsFileLoggingEnabled();

#if DEBUG
                Serilog.Debugging.SelfLog.Enable(Console.Out);
#endif
                Log.Logger = log;
                Log.Information("============ DaxStudio Startup =============");
                //SsasAssemblyResolver.Instance.BuildAssemblyCache();
                SystemInfo.WriteToLog();
                if (isLoggingKeyDown)
                {
                    log.Information($"Logging enabled due to {Constants.LoggingHotKeyName} key being held down");
                }
                if (logCmdLineSwitch)
                {
                    log.Information("Logging enabled by Excel Add-in");
                }
                Log.Information("Startup Parameters Port: {Port} File: {FileName} LoggingEnabled: {LoggingEnabled}", app.Args().Port, app.Args().FileName, app.Args().LoggingEnabled);

                AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;

                if (app.Args().TriggerCrashTest)
                {
                    throw new ArgumentException("Test Exception triggered by command line argument");
                }

                // force control tooltips to display even if disabled
                ToolTipService.ShowOnDisabledProperty.OverrideMetadata(
                    typeof(Control),
                    new FrameworkPropertyMetadata(true));

                app.Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Class: {0} Method: {1} Error: {2} Stack: {3}", "EntryPoint", "Main", ex.Message, ex.StackTrace);
#if DEBUG
                MessageBox.Show(ex.Message, "DAX Studio Standalone unhandled exception");
#else
                // use CrashReporter.Net to send bug to DrDump
                CrashReporter.ReportCrash(ex, "DAX Studio Standalone Fatal startup crash");
#endif
            }
            finally
            {
                Log.Information("============ DaxStudio Shutdown =============");
                Log.CloseAndFlush();
            }
        }
Beispiel #15
0
        private static void Main(string[] args)
        {
            //Initialize PoolManager
            //PoolManager poolManager = new PoolManager();

            //initialize settings
            //Pass PoolManager to settings for populating it

            Serilog.Core.LoggingLevelSwitch logLevel = new Serilog.Core.LoggingLevelSwitch(Serilog.Events.LogEventLevel.Debug);

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.ControlledBy(logLevel)
                         .WriteTo.Console(theme: SystemConsoleTheme.Literate, restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Verbose)
                         //.WriteTo.File(path: AppDomain.CurrentDomain.BaseDirectory + "log.txt")
                         .WriteTo.File(path: AppDomain.CurrentDomain.BaseDirectory + "Errors.txt", restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning)
                         .CreateLogger();

            Helpers.Logging.MinerProxyHeader();

            pools = Config.Settings.LoadPoolDirectory();

            Log.Verbose("Pool count: {0}", pools.Count);
            foreach (var pool in pools)
            {
                var handlers = Helpers.CoinHelper.CreateCoinHandlers(pool.mainPool.coin);

                PoolClient poolClient = new PoolClient(pool, handlers.poolHandler, handlers.minerHandler);
                poolClients.Add(poolClient);
            }
            Log.Debug("Done loading pools.");
            string key;

            while (true)
            {
                if (Console.KeyAvailable)
                {
                    key = Console.ReadKey(true).Key.ToString();

                    switch (key)
                    {
                    case "M":
                        foreach (var pool in poolClients)
                        {
                            Log.Information($"Miner Stats for [{pool.poolWorkerName}] miners");
                            foreach (var stats in pool.minerManager.GetMinerStatsList())
                            {
                                Log.Information($"Miner: {stats.workerName}");
                                Log.Information($"Hashrate Average: {(stats.hashrateHistory.Average(HashrateItem => HashrateItem.hashrate)).ToString("#,##0,Mh/s").Replace(",", ".")}");
                                Log.Information($"numberofConnects: {stats.numberOfConnects}");
                                Log.Information($"firstConnectTime: {stats.firstConnectTime}");
                                Log.Information($"lastConnectTime: {stats.lastConnectTime}");
                                Log.Information($"lastDisconnectTime: {stats.lastDisconnectTime}");
                                Log.Information($"totalConnectedTime: {stats.totalConnectedTime}");
                                Log.Information($"totalAcceptedShares: {stats.totalAcceptedShares}");
                                Log.Information($"totalRejectedShares: {stats.totalRejectedShares}");
                                Log.Information($"totalSubmittedShares: {stats.totalSubmittedShares}");
                            }
                        }


                        break;

                    case "Q":
                        Log.Information("Shutting down MineProxy..");
                        foreach (var pool in poolClients)
                        {
                            pool.minerServer.StopListening();
                            pool.Stop();
                        }
                        System.Environment.Exit(0);
                        break;

                    default:
                        Log.Information(key);
                        break;
                    }
                }
            }
        }
Beispiel #16
0
        public static void AppendLog(string managedItemId, ManagedCertificateLogItem logItem, Serilog.Core.LoggingLevelSwitch logLevelSwitch)
        {
            var log = GetLogger(managedItemId, logLevelSwitch);

            if (log != null)
            {
                if (logItem.LogItemType == LogItemType.CertficateRequestFailed)
                {
                    log.Error(logItem.Message);
                }
                else if (logItem.LogItemType == LogItemType.GeneralError)
                {
                    log.Error(logItem.Message);
                }
                else if (logItem.LogItemType == LogItemType.GeneralWarning)
                {
                    log.Warning(logItem.Message);
                }
                else
                {
                    log.Information(logItem.Message);
                }
            }
        }
Beispiel #17
0
 /// <summary>
 /// Gets a custom logger configuration
 /// </summary>
 /// <param name="connectionStringLoggingDb">connection string</param>
 /// <param name="loggingTable">name of the table</param>
 /// <param name="columnOptions">configuration of columns (excluded, additional, customized) in the table</param>
 /// <param name="levelSwitch">minimun level to log</param>
 /// <returns>custom logger configuration object</returns>
 private static Serilog.Core.Logger GetLog(string connectionStringLoggingDb,
                                           string loggingTable, Serilog.Sinks.MSSqlServer.ColumnOptions columnOptions, Serilog.Core.LoggingLevelSwitch levelSwitch)
 {
     return(new LoggerConfiguration()
            //.MinimumLevel.Information()
            .MinimumLevel.ControlledBy(levelSwitch)
            //.MinimumLevel.Override("SerilogDemo", Serilog.Events.LogEventLevel.Information)
            .WriteTo.MSSqlServer(connectionStringLoggingDb, loggingTable,
                                 columnOptions: columnOptions,
                                 autoCreateSqlTable: false
                                 )
            .CreateLogger());
 }
Beispiel #18
0
        public static void Main()
        {
            try
            {
                // add unhandled exception handler
                app.DispatcherUnhandledException           += App_DispatcherUnhandledException;
                AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
                TaskScheduler.UnobservedTaskException      += TaskSchedulerOnUnobservedTaskException;

                // Setup logging
                var levelSwitch = new Serilog.Core.LoggingLevelSwitch(Serilog.Events.LogEventLevel.Error);
                var config      = new LoggerConfiguration()
                                  .ReadFrom.AppSettings()
                                  .MinimumLevel.ControlledBy(levelSwitch);

                var logPath = Path.Combine(ApplicationPaths.LogPath, Constants.StandaloneLogFileName);
                config.WriteTo.RollingFile(logPath
                                           , retainedFileCountLimit: 10);

                log        = config.CreateLogger();
                Log.Logger = log;

                // add the custom DAX Studio accent color theme
                app.AddDaxStudioAccentColor();

                // TODO - do we need to customize the navigator window to fix the styling?
                //app.AddResourceDictionary("pack://application:,,,/DaxStudio.UI;Component/Resources/Styles/AvalonDock.NavigatorWindow.xaml");

                // then load Caliburn Micro bootstrapper
                AppBootstrapper bootstrapper = new AppBootstrapper(Assembly.GetAssembly(typeof(DaxStudioHost)), true);

                _eventAggregator = bootstrapper.GetEventAggregator();
                // read command line arguments
                app.ReadCommandLineArgs();

                // check if user is holding shift key down
                bool isLoggingKeyDown = (System.Windows.Input.Keyboard.IsKeyDown(Constants.LoggingHotKey1) ||
                                         System.Windows.Input.Keyboard.IsKeyDown(Constants.LoggingHotKey2));

                app.Args().LoggingEnabledByHotKey = isLoggingKeyDown;

                var logCmdLineSwitch = app.Args().LoggingEnabled;

#if DEBUG
                levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Information;
                Log.Debug("Information Logging Enabled due to running in debug mode");
#endif

                if (isLoggingKeyDown || logCmdLineSwitch)
                {
#if DEBUG
                    levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Verbose;
                    Log.Debug("Verbose Logging Enabled");
#else
                    levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;
                    Log.Debug("Debug Logging Enabled");
#endif
                }


#if DEBUG
                Serilog.Debugging.SelfLog.Enable(Console.Out);
#endif

                Log.Information("============ DaxStudio Startup =============");
                //SsasAssemblyResolver.Instance.BuildAssemblyCache();
                SystemInfo.WriteToLog();

                if (isLoggingKeyDown)
                {
                    Log.Information($"Logging enabled due to {Constants.LoggingHotKeyName} key being held down");
                }
                if (logCmdLineSwitch)
                {
                    Log.Information("Logging enabled by Excel Add-in");
                }
                Log.Information("Startup Parameters Port: {Port} File: {FileName} LoggingEnabled: {LoggingEnabled}", app.Args().Port, app.Args().FileName, app.Args().LoggingEnabled);
                Log.Information($"Portable Mode: {ApplicationPaths.IsInPortableMode}");

                AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;

                if (app.Args().TriggerCrashTest)
                {
                    throw new ArgumentException("Test Exception triggered by command line argument");
                }

                // force control tooltips to display even if disabled
                ToolTipService.ShowOnDisabledProperty.OverrideMetadata(
                    typeof(Control),
                    new FrameworkPropertyMetadata(true));

                // get the global options
                var options = bootstrapper.GetOptions();
                options.Initialize();


                // load selected theme
                var themeManager = bootstrapper.GetThemeManager();
                themeManager.SetTheme(options.Theme);

                //var theme = options.Theme;// "Light";
                //if (theme == "Dark") app.LoadDarkTheme();
                //else app.LoadLightTheme();

                // log startup switches
                var args = app.Args().AsDictionaryForTelemetry();
                Telemetry.TrackEvent("App.Startup", args);

                // Launch the User Interface
                app.Run();
            }
            //catch (ArgumentOutOfRangeException argEx)
            //{
            //    var st = new System.Diagnostics.StackTrace(argEx);
            //    var sf = st.GetFrame(0);
            //    if (sf.GetMethod().Name == "GetLineByOffset")
            //    {
            //        if (_eventAggregator != null) _eventAggregator.PublishOnUIThread(new OutputMessage(MessageType.Warning, "Editor syntax highlighting attempted to scan beyond the end of the current line"));
            //        Log.Warning(argEx, "{class} {method} AvalonEdit TextDocument.GetLineByOffset: {message}", "EntryPoint", "Main", "Argument out of range exception");
            //    }
            //}
            catch (Exception ex)
            {
                Log.Fatal(ex, "Class: {0} Method: {1} Error: {2} Stack: {3}", "EntryPoint", "Main", ex.Message, ex.StackTrace);
                Log.CloseAndFlush();
//#if DEBUG
//                MessageBox.Show(ex.Message, "DAX Studio Standalone unhandled exception");
//#else
                // use CrashReporter.Net to send bug to DrDump
                CrashReporter.ReportCrash(ex, "DAX Studio Standalone Fatal crash in Main() method");
//#endif
            }
            finally
            {
                Log.Information("============ DaxStudio Shutdown =============");
                Log.CloseAndFlush();
            }
        }
Beispiel #19
0
        private static void RunTraktor(string[] args)
        {
            var logLevelSwitch = new Serilog.Core.LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);

            Log.Logger = new LoggerConfiguration().MinimumLevel.ControlledBy(logLevelSwitch).WriteTo.Console(outputTemplate: "{Message}{NewLine}").WriteTo.File("Logs/.log", outputTemplate: "{Timestamp:HH:mm:ss} [{Level:u3}] {Message:lj}{NewLine}{Exception}", rollingInterval: RollingInterval.Day).CreateLogger();

            try
            {
                var config = new ConfigurationBuilder()
                             .SetBasePath(Environment.CurrentDirectory)
                             .AddCommandLine(args)
                             .AddJsonFile("appsettings.json", true, true)
                             .Build();

                Interval  = config.GetValue <TimeSpan?>("interval") ?? TimeSpan.FromMinutes(5);
                KeepAlive = config.GetValue <bool>("keepalive");
                ConnectivityScriptPath = config.GetValue <string>("connectscript");

                var logLevel = config.GetValue <string>("loglevel");
                if (!string.IsNullOrEmpty(logLevel))
                {
                    logLevelSwitch.MinimumLevel = Enum.Parse <Serilog.Events.LogEventLevel>(logLevel);
                }
                else if (System.Diagnostics.Debugger.IsAttached)
                {
                    logLevelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;
                }

                Log.Information($"Minimum log level = {logLevelSwitch.MinimumLevel}");
                AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
                {
                    LogException((Exception)e.ExceptionObject);
                };

                AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
                {
                    Log.Information("Shutting down ..");
                };

                if (logLevelSwitch.MinimumLevel == Serilog.Events.LogEventLevel.Verbose)
                {
                    Log.Information("Logging all exceptions raised (First Chance), this also includes handled exceptions.");
                    AppDomain.CurrentDomain.FirstChanceException += (sender, e) =>
                    {
                        Log.Verbose($"Exception (FC): {e.Exception}");
                    };
                }

                DisplayBindingIp();

                //Console.ReadLine();
                //return;

                Curator.CuratorConfiguration traktorConfig = LoadCuratorConfiguration(config, args);

                TraktService ts      = new TraktService();
                Curator      curator = new Curator(ts);

                if (StartCurator(curator, ts, traktorConfig))
                {
                    if (!string.IsNullOrEmpty(config.GetValue <string>("urls")))
                    {
                        var startup = new Traktor.Web.Startup(config, curator);
                        var host    = Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(x =>
                        {
                            x.ConfigureServices(startup.ConfigureServices).Configure(startup.Configure);
                        }).UseConsoleLifetime().Build().RunAsync();

                        Log.Information($"Running Traktor.Web @ {string.Join(", ", startup.Addresses)}");
                    }

                    appSettingsHash = FileService.ComputeHash("appsettings.json");
                    ChangeToken.OnChange(() => config.GetReloadToken(), () =>
                    {
                        var currentHash = FileService.ComputeHash("appsettings.json");
                        if (currentHash.SequenceEqual(appSettingsHash))
                        {
                            return;
                        }

                        appSettingsHash = FileService.ComputeHash("appsettings.json");
                        curator.UpdateConfiguration(LoadCuratorConfiguration(config, args));

                        Log.Information("Updated configuration! (Changes to Downloader settings requires a restart to take effect)");
                    });

                    ScheduleCuratorUpdates(curator, ts);
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                throw;
            }
        }