public static void ConfigureLogger(LogOptions options, IEnumerable <LogMessage> initialLogMessages = null) { LoggerFactory.AddSerilog(new LoggerConfiguration() .MinimumLevel.Is(options.LogLevel) .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger()); if (options.LogToFile) { // log on the lowest level to the log file var logFilesPath = Path.Combine(options.OutputPath, "logs"); LoggerFactory.AddFile(logFilesPath + "/log-{Date}.txt", LogLevel.Trace); } if (initialLogMessages != null) { var logger = LoggerFactory.CreateLogger("InitialLogging"); foreach (var logMessage in initialLogMessages) { logger.Log(logMessage.LogLevel, logMessage.EventId, logMessage.State, logMessage.Exception, logMessage.Formatter); } } }
private static void SetUpServiceProvider(IPlatformHelper platformHelper) { if (platformHelper == null) { throw new ArgumentNullException(nameof(platformHelper)); } var logFileLocation = Path.Combine(platformHelper.LogFolderPath, string.Format("_EFCoreCPTest_{0}.log", platformHelper.PlatformName)); var loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(LogLevel.Trace); loggerFactory.AddFile(logFileLocation, append: false); var logger = loggerFactory.CreateLogger("EFCoreCPTest"); logger.LogTrace("AppCommon.SetUpServiceProvider() called and default logger created"); logger.LogTrace("Creating the ServiceCollection instance"); var serviceCollection = new ServiceCollection() .AddSingleton <ILoggerFactory>(loggerFactory) .AddSingleton(logger) .AddSingleton(platformHelper) .AddLogging(); logger.LogTrace("Building the ServiceProvider instance"); ServiceProvider = serviceCollection.BuildServiceProvider(); logger.LogTrace("AppCommon.SetUpServiceProvider() returning"); }
public static void Main(string[] args) { var configuration = new ConfigurationBuilder() .AddCommandLine(args) .Build(); var loggerFactory = new LoggerFactory() .AddDebug() .AddConsole(LogLevel.Trace); configuration = Startup.LoadConfiguration(loggerFactory, configuration.GetValue <string>("config"), args); var startupOptions = configuration.GetStartupOptions(); var loggingOptions = configuration.GetLoggingOptions(); loggerFactory.AddFile(startupOptions.Name, loggingOptions.LogFolder); var webHost = new WebHostBuilder() .ConfigureServices(s => s.AddSingleton(configuration)) .UseLoggerFactory(loggerFactory) .UseConfiguration(configuration) .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel() .UseStartup <LinuxStartup>() .Build(); try { webHost.Run(); } catch (Exception ex) { ex.HandleWebHostStartExceptions(webHost.Services.GetService <IServiceProvider>(), true); } }
public static ILogger GetLogger() { var loggerFactory = new LoggerFactory(); loggerFactory.AddFile(Path.Combine(Directory.GetCurrentDirectory(), "logInfo.txt")); return(loggerFactory.CreateLogger("FileLogger")); }
private static ILogger ConfigureLogger() { var loggingSection = ConfigurationService.Root.GetSection("logging"); var loggingSettings = ConfigurationService.Root.GetSection("logging")?.Get <LoggingSettings>(); var resultLogger = default(ILogger); if (loggingSettings != null && loggingSettings.IsEnabled) { ILoggerFactory loggerFactory = new LoggerFactory(); if (loggingSettings.IsConsoleLoggingEnabled) { loggerFactory.AddConsole(loggingSection); } if (loggingSettings.IsDebugLoggingEnabled) { loggerFactory.AddDebug(); } if (loggingSettings.IsFileLoggingEnabled) { var fileLoggingSection = ConfigurationService.Root.GetSection("logging:fileLogging"); loggerFactory.AddFile(fileLoggingSection); } resultLogger = loggerFactory.CreateLogger("Bellatrix"); } return(resultLogger); }
public static void ConfigureLogger(LogOptions options, IEnumerable <LogMessage> initialLogMessages = null) { LoggerFactory.AddSerilog(new LoggerConfiguration().MinimumLevel.Is(options.LogLevel).Enrich.FromLogContext().WriteTo.Console().CreateLogger()); if (options.LogToFile) { // log on the lowest level to the log file var logFilesPath = Path.Combine(options.OutputPath, "logs"); LoggerFactory.AddFile(logFilesPath + "/log-{Date}.txt", MSLogLevel.Trace); } if (initialLogMessages != null) { var logger = LoggerFactory.CreateLogger("InitialLogging"); foreach (var logMessage in initialLogMessages) { logger.Log(logMessage.LogLevel, logMessage.EventId, logMessage.State, logMessage.Exception, logMessage.Formatter); } } // When stryker log level is debug or trace, set LibGit2Sharp loglevel to info if (options.LogLevel < LogEventLevel.Information) { var libGit2SharpLogger = LoggerFactory.CreateLogger(nameof(LibGit2Sharp)); GlobalSettings.LogConfiguration = new LogConfiguration(LibGitLogLevel.Info, (level, message) => libGit2SharpLogger.Log(LogLevelMap[level], message)); } }
public static LoggerFactory GetFactory(LogLevel level, string fileName = M_LogFileName) { if (string.IsNullOrEmpty(fileName)) { fileName = M_LogFileName; } if (fileName == M_LogFileName && LogConfig.Config.SplitLevel) { fileName += $".{level.ToString().ToLower()}"; } if (!m_factorys.ContainsKey(fileName)) { lock (m_factorys) { if (!m_factorys.ContainsKey(fileName)) { var logPath = GetLogPath(); var pathFormat = System.IO.Path.Combine(logPath, LogConfig.Config.FileFormat.Replace("@FileName", fileName)); var factory = new LoggerFactory(); factory.AddDebug(); factory.AddConsole(LogConfig.Config.LogLevel, true); factory.AddFile(pathFormat, LogConfig.Config.LogLevel); m_factorys.Add(fileName, factory); } } } return(m_factorys[fileName]); }
public JobListener() { LoggerFactory factory = new LoggerFactory(); factory.AddFile(LogLevel.Debug); logger = factory.CreateLogger <JobListener>(); }
public static void ConfigureLogger(LogOptions options, IEnumerable <LogMessage> initialLogMessages = null) { LoggerFactory.AddSerilog(new LoggerConfiguration() .MinimumLevel.Is(options.LogLevel) .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger()); if (options.LogToFile) { // log on the lowest level to the log file var logFilesPath = Path.Combine(options.OutputPath, "logs"); LoggerFactory.AddFile(logFilesPath + "/log-{Date}.txt", LogLevel.Trace); } if (initialLogMessages != null) { var logger = LoggerFactory.CreateLogger("InitialLogging"); foreach (var logMessage in initialLogMessages) { // Create the generic variant of the method to make sure any consumer can use typeof(TState) _logMethodInfo.MakeGenericMethod(logMessage.StateType) .Invoke( logger, new[] { logMessage.LogLevel, logMessage.EventId, logMessage.State, logMessage.Exception, logMessage.Formatter }); } } }
/// <summary> /// Example using manager without DI framework (not recommended). /// </summary> // ReSharper disable once InconsistentNaming // ReSharper disable once UnusedMember.Local private static void ExampleMainWithoutDI() { try { // Load configuration. var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", true, false) .Build(); // Get configuration settings. var symbols = configuration.GetSection("TradeHistory:Symbols").Get <string[]>() ?? new string[] { Symbol.BTC_USDT }; var limit = 25; try { limit = Convert.ToInt32(configuration.GetSection("TradeHistory")?["Limit"]); } catch { /* ignore */ } var loggerFactory = new LoggerFactory(); loggerFactory.AddFile(configuration.GetSection("Logging:File")); // Initialize all the things... a DI framework could instantiate for you... var api = new BinanceApi(BinanceHttpClient.Instance, logger: loggerFactory.CreateLogger <BinanceApi>()); var tradeClient = new AggregateTradeClient(loggerFactory.CreateLogger <AggregateTradeClient>()); var webSocket = new DefaultWebSocketClient(logger: loggerFactory.CreateLogger <DefaultWebSocketClient>()); var stream = new BinanceWebSocketStream(webSocket, loggerFactory.CreateLogger <BinanceWebSocketStream>()); var controller = new BinanceWebSocketStreamController(api, stream, loggerFactory.CreateLogger <BinanceWebSocketStreamController>()); var publisher = new BinanceWebSocketStreamPublisher(controller, loggerFactory.CreateLogger <BinanceWebSocketStreamPublisher>()); var client = new AggregateTradeWebSocketClient(tradeClient, publisher, loggerFactory.CreateLogger <AggregateTradeWebSocketClient>()); var cache = new AggregateTradeWebSocketCache(api, client, loggerFactory.CreateLogger <AggregateTradeWebSocketCache>()); // Add error event handler. controller.Error += (s, e) => HandleError(e.Exception); foreach (var symbol in symbols) { // Subscribe to symbol with callback. cache.Subscribe(symbol, limit, Display); lock (_sync) { _message = symbol == symbols.Last() ? $"Symbol: \"{symbol}\" ...press any key to exit." : $"Symbol: \"{symbol}\" ...press any key to continue."; } Console.ReadKey(true); // Unsubscribe from symbol. cache.Unsubscribe(); } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(); Console.WriteLine(" ...press any key to close window."); Console.ReadKey(true); } }
private static LoggerFactory CreateLogger(string outputPath, out ILogger logger) { var factory = new LoggerFactory(); logger = factory.CreateLogger("User Import Server EF Core"); factory.AddFile(outputPath, LogLevel.Debug); return(factory); }
public static void Init(IConfiguration configuration) { //Factory.AddConsole( LogLevel.Trace, includeScopes: true ); Factory.AddConsole(configuration.GetSection("Logging")); Factory.AddFile("logs/checklinks-{Date}.json", isJson: true, minimumLevel: LogLevel.Trace); }
/// <summary> /// Initializes a new instance of the <see cref="T:MobileManager.Logging.Logger.Logger"/> class. /// </summary> public ManagerLogger() { ILoggerFactory loggerFactory = new LoggerFactory() .AddConsole() .AddDebug(); loggerFactory.AddFile("Logs/log-{Date}.txt", LogLevel.Trace); _logger = loggerFactory.CreateLogger("MobileManager"); }
static FileLogging() { var date = System.DateTime.Today; _fileName = Assembly.GetExecutingAssembly().GetName().Name; PhysicalPath = Path.Combine($"logs", _fileName); Factory.AddSerilog(); Factory.AddFile(PhysicalPath); }
public App() { var serviceCollection = new ServiceCollection() .AddLogging() .AddChimpLogging() .AddSingleton <MainViewModel>() .AddSingleton <MainWindow>() .AddSingleton <SynchronizationContext>(new DispatcherSynchronizationContext(Dispatcher)); ConfigureValidators(serviceCollection); ConfigureDetectors(serviceCollection); ConfigureProviders(serviceCollection); ConfigureContainers(serviceCollection); ConfigureServices(serviceCollection); ConfigureOptions(serviceCollection); ServiceProvider = serviceCollection.BuildServiceProvider(); LoggerFactory = ServiceProvider.GetService <ILoggerFactory>(); var args = Environment.GetCommandLineArgs(); var logLevel = LogLevel.Information; var args1 = args.Skip(1); if (args1.Contains("/verbose")) { logLevel = LogLevel.Trace; } else if (args1.Contains("/debug")) { logLevel = LogLevel.Debug; } var chdkTempPath = Path.Combine(Path.GetTempPath(), "CHIMP"); var filePath = Path.Combine(chdkTempPath, "CHIMP.log"); LoggerFactory.AddFile(filePath, logLevel, retainedFileCountLimit: 8); Logger = LoggerFactory.CreateLogger <App>(); var assembly = Assembly.GetExecutingAssembly(); Logger.LogInformation(assembly.FullName); var config = assembly.GetCustomAttribute <AssemblyConfigurationAttribute>(); Logger.LogInformation("Configuration: {0}", config.Configuration); Logger.LogObject(LogLevel.Information, args); Logger.LogInformation(OperatingSystem.DisplayName); Logger.LogInformation("64-bit: {0}", Environment.Is64BitProcess); Logger.LogInformation("Version: {0}", OperatingSystem.Version); Logger.LogInformation("Processors: {0}", Environment.ProcessorCount); ViewModel = ServiceProvider.GetService <MainViewModel>(); DialogService = ServiceProvider.GetService <IDialogService>(); DispatcherUnhandledException += App_DispatcherUnhandledException; }
public void Configuration(IAppBuilder app) { ConfigureAuth(app); var factory = new LoggerFactory(); factory.AddFile(); LoggerHelper.Logger = factory.CreateLogger("SaleManagement"); LoggerHelper.Logger.LogInformation("程序启动"); ConfigureAutoMapper(); }
public static void Main(string[] args) { //while (!Debugger.IsAttached) { // Thread.Sleep(1000); //} var configuration = new ConfigurationBuilder() .AddCommandLine(args) .Build(); var loggerFactory = new LoggerFactory() .AddDebug() .AddConsole(LogLevel.Trace); var startupOptions = configuration.GetStartupOptions(); if (startupOptions != null && startupOptions.IsService) { loggerFactory.AddEventLog(new EventLogSettings { Filter = (_, logLevel) => logLevel >= LogLevel.Warning, SourceName = Resources.Text_ServiceName }); } configuration = Startup.LoadConfiguration(loggerFactory, configuration.GetValue <string>("config"), args); var loggingOptions = configuration.GetLoggingOptions(); var name = startupOptions != null ? startupOptions.Name : "RTVS"; var logFolder = loggingOptions != null ? loggingOptions.LogFolder : Environment.GetEnvironmentVariable("TEMP"); loggerFactory.AddFile(name, logFolder); var webHost = new WebHostBuilder() .ConfigureServices(s => s.AddSingleton(configuration)) .UseLoggerFactory(loggerFactory) .UseConfiguration(configuration) .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel() .UseStartup <WindowsStartup>() .Build(); if (startupOptions != null && startupOptions.IsService) { ServiceBase.Run(new BrokerService(webHost)); } else { try { webHost.Run(); } catch (Exception ex) { ex.HandleWebHostStartExceptions(webHost.Services.GetService <IServiceProvider>(), true); } } }
public static void ConfigureLogger(LogOptions options) { LoggerFactory.AddSerilog(new LoggerConfiguration() .MinimumLevel.Is(options.LogLevel) .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger()); if (options.LogToFile) { // log on the lowest level to the log file LoggerFactory.AddFile("StrykerLogs/log-{Date}.txt", LogLevel.Trace); } }
public static void ConfigureLogger(LogOptions options) { LoggerFactory.AddSerilog(new LoggerConfiguration() .MinimumLevel.Is(options.LogLevel) .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger()); if (options.LogToFile) { // log on the lowest level to the log file var logFilesPath = Path.Combine(options.OutputPath, "logs"); LoggerFactory.AddFile(logFilesPath + "/log-{Date}.txt", LogLevel.Trace); } }
public void Configuration(IAppBuilder app) { ConfigureAuth(app); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); BundleTable.Bundles.RegisterConfigurationBundles(); ////BundleTable.EnableOptimizations = true; ConfigureAutoMapper(); AntiForgeryConfig.UniqueClaimTypeIdentifier = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"; var factory = new LoggerFactory(); factory.AddFile(); LoggerHelper.Logger = factory.CreateLogger("SaleManagement"); LoggerHelper.Logger.LogInformation("程序启动"); }
private void InitializeServices() { const string ConnectionString = @"Server=(localdb)\MSSQLLocalDB;Database=FootballTeam;Trusted_Connection=True;"; var loggerFactory = new LoggerFactory(); loggerFactory.AddFile("Logs/queries.txt"); var services = new ServiceCollection(); services.AddTransient <UnitOfWork>() .AddSingleton(loggerFactory) .AddEntityFrameworkSqlServer() .AddDbContext <TeamContext>(options => options.UseSqlServer(ConnectionString)); Container = services.BuildServiceProvider(); }
static void Main(string[] args) { var serverName = EnvManager.FindArgumentValue("server"); var configPathes = EnvManager.FindArgumentValues("config"); if (string.IsNullOrEmpty(serverName) || (configPathes.Count < 1)) { Console.WriteLine("You need to provide serverName and at least one config path!"); Console.WriteLine("Closing..."); Console.ReadKey(); return; } var loggerFactory = new LoggerFactory(); if (EnvManager.HasArgument("-console-log")) { loggerFactory.AddConsole(CustomLogFilter); } loggerFactory.AddFile("log.txt", false); var messageFormat = MessageFormat.LastTaskFailMessage; var consoleService = new ConsoleService(loggerFactory, messageFormat); var services = new List <IService> { consoleService, new SlackService(loggerFactory, messageFormat), new StatService("stats.xml", loggerFactory, true) }; services.TryAddNotificationService(loggerFactory); var commandFactory = new CommandFactory(loggerFactory); var server = new BuildServer(commandFactory, loggerFactory, serverName); string startUpError = null; if (!server.TryInitialize(out startUpError, services, configPathes)) { Console.WriteLine(startUpError); Console.WriteLine("Closing..."); Console.ReadKey(); return; } Console.WriteLine($"{server.ServiceName} started and ready to use."); consoleService.Process(); }
public static void ConfigureLogger(LogEventLevel logLevel, bool logToFile, string outputPath) { LoggerFactory.AddSerilog(new LoggerConfiguration().MinimumLevel.Is(logLevel).Enrich.FromLogContext().WriteTo.Console().CreateLogger()); if (logToFile) { // log on the lowest level to the log file var logFilesPath = Path.Combine(outputPath, "logs"); LoggerFactory.AddFile(logFilesPath + "/log-{Date}.txt", MSLogLevel.Trace); } // When stryker log level is debug or trace, set LibGit2Sharp loglevel to info if (logLevel < LogEventLevel.Information) { var libGit2SharpLogger = LoggerFactory.CreateLogger(nameof(LibGit2Sharp)); GlobalSettings.LogConfiguration = new LogConfiguration(LibGitLogLevel.Info, (level, message) => libGit2SharpLogger.Log(LogLevelMap[level], message)); } }
public SmartSqlFixture() { LoggerFactory = new LoggerFactory(Enumerable.Empty <ILoggerProvider>(), new LoggerFilterOptions { MinLevel = LogLevel.Debug }); var logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", "SmartSql.log"); LoggerFactory.AddFile(logPath, LogLevel.Trace); SmartSqlBuilder = new SmartSqlBuilder() .UseXmlConfig() .UseLoggerFactory(LoggerFactory) .UseAlias(GLOBAL_SMART_SQL) .Build(); DbSessionFactory = SmartSqlBuilder.DbSessionFactory; SqlMapper = SmartSqlBuilder.SqlMapper; }
public SmartSqlFixture() { LoggerFactory = new LoggerFactory(Enumerable.Empty <ILoggerProvider>(), new LoggerFilterOptions { MinLevel = LogLevel.Debug }); var logPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", "SmartSql.log"); LoggerFactory.AddFile(logPath, LogLevel.Trace); SmartSqlBuilder = new SmartSqlBuilder() .UseXmlConfig() .UseLoggerFactory(LoggerFactory) .UseAlias(GLOBAL_SMART_SQL) .AddFilter <TestPrepareStatementFilter>() .RegisterEntity(typeof(AllPrimitive)) // .RegisterEntity(new TypeScanOptions // { // AssemblyString = "SmartSql.Test", // Filter = type => type.Namespace == "SmartSql.Test.Entities" // }) .UseCUDConfigBuilder() .Build(); DbSessionFactory = SmartSqlBuilder.DbSessionFactory; SqlMapper = SmartSqlBuilder.SqlMapper; RepositoryBuilder = new EmitRepositoryBuilder(null, null, LoggerFactory.CreateLogger <EmitRepositoryBuilder>()); RepositoryFactory = new RepositoryFactory(RepositoryBuilder, LoggerFactory.CreateLogger <RepositoryFactory>()); UsedCacheRepository = RepositoryFactory.CreateInstance(typeof(IUsedCacheRepository), SqlMapper) as IUsedCacheRepository; AllPrimitiveRepository = RepositoryFactory.CreateInstance(typeof(IAllPrimitiveRepository), SqlMapper) as IAllPrimitiveRepository; UserRepository = RepositoryFactory.CreateInstance(typeof(IUserRepository), SqlMapper) as IUserRepository; ColumnAnnotationRepository = RepositoryFactory.CreateInstance(typeof(IColumnAnnotationRepository), SqlMapper) as IColumnAnnotationRepository; InitTestData(); }
public static ILogger GetFileLogger(string identity) { if (!loggers.ContainsKey(identity)) { LoggerFactory factory = new LoggerFactory(); string directoryPath = Path.Combine(Directory.GetCurrentDirectory(), defaultDir); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } factory.AddFile(Path.Combine(directoryPath, string.Format("{0}.txt", identity))); loggers.Add(identity, factory.CreateLogger(identity)); } return(loggers[identity]); }
public CampEFCoreService(CampDbContext db) : base() { DbContext = db; CampCategories = new CampCategoryRepository(db); CampBatches = new CampBatchRepository(db); Camps = new CampRepository(db); Diets = new DietRepository(db); Instructors = new InstructorRepository(db); InstructorRoles = new InstructorRoleRepository(db); ObjectOrders = new ObjectOrderRepository(db); Objects = new ObjectRepository(db); ObjectTypePrices = new ObjectTypePriceRepository(db); ObjectTypes = new ObjectTypeRepository(db); Payments = new PaymentRepository(db); Photos = new PhotoRepository(db); Context = new HttpContextAccessor(); LoggerFactory = new LoggerFactory(); LoggerFactory.AddFile("Logs/{Date}.txt"); Logger = LoggerFactory.CreateLogger("Log"); }
static void Main(string[] args) { if (args.Length == 0) { InputParamsHelper.DisplayHelp(); //Exit after displaying help prompt; } Parameters = InputParamsHelper.ParseCommandLineParams(args); LoggerFactory.AddFile("Logs/ServerLogMonitoringLog-{Date}.txt"); Logger = LoggerFactory.CreateLogger <Program>(); List <ServerLogFileInfo> serverLogFileInfoList = GetServerLogFileInfo(); //Get the files.csv as cv collection List <ServerLogFactInfo> serverLogFactInfoList = GetServerLogFileFactInfo(); // Get the file status.cs as collection WriteCsvFileFinally(serverLogFileInfoList, serverLogFactInfoList); //Write the final sliced data sets as csv to file System.Console.WriteLine("\n\nRefer to the log folder for more details. "); System.Console.WriteLine("\n\nPress any key to exit"); System.Console.ReadKey(); Environment.Exit(0); }
ILoggerFactory ConfigureLogging(BackupUtilityConfiguration config) { var loggerFactory = new LoggerFactory(); foreach (var log in config.Logging) { switch (log.Type) { case LogType.Console: { loggerFactory.AddConsole(log.Level); } break; case LogType.File: { loggerFactory.AddFile("{Date}.txt", log.Level); } break; } } return(loggerFactory); }
private static IHost CreateHost() { return(new HostBuilder() .ConfigureServices(services => { var Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false) .AddEnvironmentVariables() .Build(); Config.LoadConfig(Configuration); }) .ConfigureLogging(builder => { builder.AddConsole(); var logName = Config.LogPath + $"stresstest-{DateTime.Now.Date.ToString("yyyy'-'MM'-'dd")}.txt"; //Directory.GetCurrentDirectory(); //$"C:/inetpub/logs/LogFiles/"; var loggerFactory = new LoggerFactory(); loggerFactory.AddFile(logName); SimpleLogger.Factory = loggerFactory; }) .Build()); }