private void SetupLogger() { const string format = "${longdate} ${message} ${exception:format=tostring}"; var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget() { FileName = "SpotifyLyrics.log", Name = "logfile", Layout = new SimpleLayout(format), Encoding = Encoding.UTF8, }; config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logfile)); #if DEBUG var logconsole = new NLog.Targets.ConsoleTarget() { Name = "logconsole", Layout = new SimpleLayout(format), Encoding = Encoding.UTF8, }; config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logconsole)); #endif NLog.LogManager.Configuration = config; }
static void SetupLogging(string path) { var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = path, FileNameKind = NLog.Targets.FilePathKind.Absolute, Layout = "${longdate} ${level:uppercase=true} ${logger}: ${message} ${exception:format=tostring}", ArchiveAboveSize = 1024 * 1024 * 8, MaxArchiveFiles = 10 }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole") { Layout = "${longdate} ${level:uppercase=true} ${logger}: ${message} ${exception:format=tostring}" }; #if DEBUG config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); #endif config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); NLog.LogManager.Configuration = config; }
public void RunBeforeAnyTests() { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "unit-test.log" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); var logdebugger = new NLog.Targets.DebuggerTarget("logdebugger"); // Rules for mapping loggers to targets config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole); config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logfile); config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logdebugger); // Apply config NLog.LogManager.Configuration = config; var serviceProvider = new ServiceCollection() .AddLogging(logger => { logger.SetMinimumLevel(LogLevel.Trace); }) .BuildServiceProvider(); LogFactory = serviceProvider.GetService <ILoggerFactory>(); LogFactory.AddNLog(); }
static void Main(string[] args) { var minLevel = LogLevel.Info; var debugMode = args.Any(c => c.Equals("debug", StringComparison.CurrentCultureIgnoreCase)); var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logFile = new NLog.Targets.FileTarget("logfile") { FileName = ".log" }; var logConsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets if (debugMode) { minLevel = LogLevel.Debug; config.AddRule(LogLevel.Trace, LogLevel.Fatal, logConsole); } config.AddRule(minLevel, LogLevel.Fatal, logFile); // Apply config LogManager.Configuration = config; // CronWorker.Start(); Thread.Sleep(Timeout.Infinite); }
public MainWindow() { InitializeComponent(); Title = $"报告自动校核 v{Application.ResourceAssembly.GetName().Version.ToString()}"; //TODO:movetofunction Top = 0.3 * (App.ScreenHeight - Height); Left = 0.4 * (App.ScreenWidth - Width); //this.Left = ScreenWidth - this.ActualWidth * 1.3; //Nlog var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = @"Log\LogFile.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config LogManager.Configuration = config; log = LogManager.GetCurrentClassLogger(); CheckForUpdateInStarup(); //启动时检查更新 }
private static void ConfigureLogging() { var config = new NLog.Config.LoggingConfiguration(); var logFile = new NLog.Targets.FileTarget("logfile") { Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss.fff}|${level:uppercase=true}|${logger:shortName=True}|${message:withexception=true}", FileName = "./logging/InventoryKamera.log", ArchiveFileName = "logging/archives/InventoryKamera.{####}.log", ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMddHHmmss", MaxArchiveFiles = 4, ConcurrentWrites = true, KeepFileOpen = true, ArchiveOldFileOnStartup = true, ArchiveFileKind = NLog.Targets.FilePathKind.Relative }; var logConsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logConsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logFile); LogManager.Configuration = config; }
public Log() { var config = new NLog.Config.LoggingConfiguration(); var assembly = System.Reflection.Assembly.GetEntryAssembly(); var name = assembly.GetName().Name; // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget(name) { FileName = "${basedir}/logs/${logger}/${shortdate}.log", Layout = "${longdate} ${aspnet-request:servervariable=URL}[${uppercase:${level}}] ${message} ${exception:format=toString,Data:maxInnerExceptionLevel=10}" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole") { Layout = "${longdate} ${aspnet-request:servervariable=URL}[${uppercase:${level}}] ${message} ${exception:format=toString,Data:maxInnerExceptionLevel=10}" }; // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config; }
public void RegisterLogger(string logFilename) { var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget { FileName = logFilename, Name = "logfile", Layout = "${longdate}|${level:uppercase=true}|${logger}|${message}|${exception:format=ToString,StackTrace}${newline}" }; var logconsole = new NLog.Targets.ConsoleTarget { Name = "logconsole", Layout = "${longdate}|${level:uppercase=true}|${logger:shortName=true}|${message}" }; config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logconsole)); config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Warn, logfile)); config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Error, logfile)); LogManager.Configuration = config; _container.RegisterConditional(typeof(ILogger), context => typeof(NLogProxy <>).MakeGenericType(context.Consumer.ImplementationType), Lifestyle.Singleton, context => true); }
public static ILogger GetLogger(string className, CultureInfo defaultCultureInfo) { if (ReferenceEquals(className, null)) { throw new ArgumentNullException($"{nameof(className)} is null."); } var config = new NLog.Config.LoggingConfiguration(); var logFile = new NLog.Targets.FileTarget() { FileName = "log.txt", Name = "logfile" }; var logConsole = new NLog.Targets.ConsoleTarget() { Name = "logconsole" }; config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logConsole)); config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logFile)); config.DefaultCultureInfo = defaultCultureInfo; LogManager.Configuration = config; var logger = LogManager.GetLogger(className); return(new NLoggerAdapter(logger)); }
private static (ILogger, IDisposable) InitializeLogger() { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "log.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); var dispose = new AnonymousDisposable(() => { logfile.Dispose(); logconsole.Dispose(); }); // Rules for mapping loggers to targets config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Error, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config; return(NLog.LogManager.GetCurrentClassLogger(), dispose); }
public void ConfigNLogToUseAWSCloudWatch() { var config = new LoggingConfiguration(); //I would have preferred to have this configured on NLog.config //However, Region is required and I don't want to duplicated //Reason why it is implemented here - NO DUPLICATIONS!! lol var awsTarget = new AWSTarget() { LogGroup = "Paulo-Forro-GroupLogs", Region = _aWSRegionEndpoint }; config.AddTarget("aws", awsTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, awsTarget)); //Write other logs destinations as well var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Info, LogLevel.Fatal, logfile); LogManager.Configuration = config; }
/// <summary> /// Zwraca skonfigurowany obiekt Logger /// </summary> /// <param name="name">Nazwa loggera (nazwa pliku tekstowego czerpie tę nazwę)</param> /// <param name="minLogLevel">Minimalny poziom logowania do pliku</param> /// <param name="showAllOnConsole">Czy mają być wyświetlane informacje na konsoli (wtedy wyświetlane są wszystkie logi)</param> /// <returns>Logger pozwalający na zapis do pliku oraz ewentualnie do pisana na konsoli</returns> private static Logger CreateLogger(string name, LogLevel minLogLevel, bool showAllOnConsole = false) { if (string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name)) { name = "NoName"; } var config = new NLog.Config.LoggingConfiguration(); if (showAllOnConsole) { var logconsole = new NLog.Targets.ConsoleTarget("logconsole") { Layout = "${longdate} ${callsite} ${level} -> ${message}" }; config.AddRule(LogLevel.Trace, LogLevel.Fatal, logconsole); } string logLocation = "/temp/"; string fileNameAndLocation = $"{logLocation}{name}.nlog.txt"; var logfile = new NLog.Targets.FileTarget("logfile") { FileName = fileNameAndLocation, Layout = "${longdate} ${callsite} ${level} -> ${message}" }; config.AddRule(minLogLevel, LogLevel.Fatal, logfile); LogManager.Configuration = config; return(LogManager.GetLogger(name)); }
internal NLogLogger(IFileSystem fileSystem, string applicationName) { var config = new LoggingConfiguration(); var consoleTarget = new NLog.Targets.ConsoleTarget(); config.AddTarget("console", consoleTarget); consoleTarget.Layout = "${longdate}|${level}|${message}"; var fileTarget = new NLog.Targets.FileTarget(); string localApplicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string logPath = fileSystem.Path.Combine(localApplicationData, "Flagstone", applicationName, applicationName + ".txt"); fileTarget.FileName = logPath; fileTarget.ArchiveAboveSize = 10 * 1024 * 1024; fileTarget.MaxArchiveFiles = 10; fileTarget.Layout = "${longdate}|${level}|${message}"; var consoleRule = new LoggingRule("*", LogLevel.Info, consoleTarget); var fileRule = new LoggingRule("*", LogLevel.Trace, fileTarget); config.LoggingRules.Add(consoleRule); config.LoggingRules.Add(fileRule); LogManager.Configuration = config; m_logger = LogManager.GetLogger(String.Empty); }
private SteuerungLogic() { //nlog versuche: var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: Console var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); // Apply config NLog.LogManager.Configuration = config; var logger = NLog.LogManager.GetCurrentClassLogger(); logger.Info("hello steuerungentfeuchter 2"); StateMachine = new StateMachineLogic(); //StateMachine init StateMachine.CurrentState = State.Aus; StateMachine._transitions.Add(new StatesTransition(State.Aus, Signal.GotoWaitForAction, GotoStateWaitForAction, State.WaitForAction)); StateMachine._transitions.Add(new StatesTransition(State.WaitForAction, Signal.GotoAus, GotoStateAus, State.Aus)); StateMachine._transitions.Add(new StatesTransition(State.WaitForAction, Signal.GotoAction, GotoStateAction, State.Action)); StateMachine._transitions.Add(new StatesTransition(State.Action, Signal.GotoAus, GotoStateAus, State.Aus)); StateMachine._transitions.Add(new StatesTransition(State.Action, Signal.GotoWaitForAction, GotoStateWaitForAction, State.WaitForAction)); }
private static void InitLogging() { var config = new NLog.Config.LoggingConfiguration(); var exeDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); var logDirectory = Path.Combine(exeDirectory, "logs"); Directory.CreateDirectory(logDirectory); var logfileName = DateTime.Now.ToString("yyyy-MM-dd(HHmm)") + ".txt"; var logfilePath = Path.Combine(logDirectory, logfileName); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = logfilePath }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config LogManager.Configuration = config; }
public static async Task Main(string[] args) { var builder = new HostBuilder() .ConfigureAppConfiguration((hostingContext, config) => { config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) .ConfigureServices((hostContext, services) => { services.AddOptions(); services.AddSingleton <ISettings, Settings.Settings>(); services.AddSingleton <IHostedService, AgentService>(); services.AddSingleton <IUpdater, GatewayUpdater>(); services.AddSingleton <IInstallManager, InstallManager>(); }) .ConfigureLogging((hostingContext, logging) => { #if DEBUG var t = new NLog.Targets.ConsoleTarget(); var config = NLog.LogManager.Configuration; config.LoggingRules[0].Targets.Clear(); config.LoggingRules[0].Targets.Add(t); NLog.LogManager.Configuration = config; #endif logging.AddNLog(); }); await builder.RunConsoleAsync(); }
public override void Load() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); // Setup Nlog Config var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole); config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logfile); NLog.LogManager.Configuration = config; IConfigurationRoot configuration = builder.Build(); Bind <IConfiguration>().ToConstant(configuration); Bind <IValidator>().To <FlightValidator>(); Bind <IEventReader>().To <EventReader>(); Bind <IEventProcessor>().To <FlightEventProcessor>(); Bind <IRule>().To <FlightMatchingRule>(); Bind <IRule>().To <PassengerMatchingRule>(); Bind <ILogger>().To <FlightEventLogger>(); Bind <IWatcher>().To <FlightWatcher>(); Bind <IEventHandler>().To <FlightEventHandler>(); Bind <IEventProcessingHandler>().To <EventProcessingHandler>(); Bind <IErrorsProcessingHandler>().To <ErrorsProcessingHandler>(); Bind <ILogWriter>().To <ConsoleLogWriter>(); }
/// <summary> /// https://code-maze.com/net-core-web-development-part3/ /// Used https://stackoverflow.com/questions/61553415/using-nlog-console-logging-together-in-net-core-console-app /// </summary> /// <param name="services"></param> public void SetupServices(IServiceCollection services) { services.AddTransient <ILoggerManager, LoggerManager>(); var config = new LoggingConfiguration(); if (File) { var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "log.txt" }; config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); } if (Console) { var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); } // Apply config NLog.LogManager.Configuration = config; var logger = LogManager.GetCurrentClassLogger(); logger.Info($"Completed Setup of NLog"); }
private static LogFactory BuildLogFactory2() { LogFactory logFactory = new LogFactory(); var config = new LoggingConfiguration(); var logconsole = new NLog.Targets.ConsoleTarget("logconsole") { Layout = @"[${date:format=HH\:mm\:ss | fff}ms | Id ${pad:padding=3:inner=#${logger}} | ${pad:padding=5:inner=#${level:uppercase=true}}] : ${message}${when:when=length('${exception}')>0:Inner= | EXCEPTION}", }; var logfile = new NLog.Targets.FileTarget("logfile") { Layout = @"[${date:format=yyyy-MM-dd HH\:mm\:ss | fff}ms | ${pad:padding=3:inner=#${logger:format=00}} | ${pad:padding=6:inner=#${level:uppercase=true}}] : ${message}${when:when=length('${exception}')>0:inner=${exception:format=tostring}:}", FileName = "file.txt", FileNameKind = NLog.Targets.FilePathKind.Relative, }; var logsentinel = new NLog.Targets.NLogViewerTarget("logsentinel") { IncludeSourceInfo = true, Address = "tcp://127.0.0.1:9999", Layout = logfile.Layout, }; config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logsentinel); logFactory.Configuration = config; return(logFactory); }
static void Main(string[] args) { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config LogManager.Configuration = config; int i = 0; while (true) { try { Logger.Info(i++); } catch (Exception ex) { Logger.Error(ex, "Goodbye cruel world"); break; } } NLog.LogManager.Shutdown(); }
static void Main(string[] args) { var config = new NLog.Config.LoggingConfiguration(); var logFile = new NLog.Targets.FileTarget("logfile") { FileName = "log.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logConsole"); NLog.Logger log = NLog.LogManager.GetCurrentClassLogger(); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logFile); NLog.LogManager.Configuration = config; IFileHandler fileHandler = new TxtFileHandler("Persons.txt"); try { Person[] persons = fileHandler.ReadData(); foreach (var person in persons) { Console.WriteLine($"{person.FirstName} - {person.LastName} of age: {person.Age}"); } FunStatistics stats = new FunStatistics(); stats.CrunchTheNumbers(persons); Console.WriteLine($"Most found letter in the names: {stats.MostFoundLetter()}"); stats.PrinAll(); } catch (MyCustomException ex) { log.Error($"Exception message: {ex.Message}, Stacktrace: {ex.StackTrace}, "); } }
public NLoggerFactory(JimuNLogOptions options = null) { options = options ?? new JimuNLogOptions { EnableConsoleLog = true }; if (!string.IsNullOrEmpty(options.Configuration)) { N.LogManager.Configuration = new N.Config.XmlLoggingConfiguration(options.Configuration); } else { var config = new N.Config.LoggingConfiguration(); //var ip = JimuHelper.GetLocalIPAddress(); if (options.EnableFileLog) { var fileConf = new N.Targets.FileTarget("jimuLogFile") { ArchiveAboveSize = 10000000, Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level:uppercase=true} [${threadid}] ${message}" }; string path = string.IsNullOrEmpty(options.FileLogPath) ? "./log" : options.FileLogPath; fileConf.FileName = path + "/${shortdate}.log"; config.AddRule(ConvertToLevel(options.FileLogLevelMin), ConvertToLevel(options.FileLogLevelMax), fileConf); } if (options.EnableConsoleLog) { var consoleLog = new N.Targets.ConsoleTarget("jimuLogconsole") { Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level:uppercase=true} [${threadid}] ${message}" }; config.AddRule(ConvertToLevel(options.ConsoleLogLevelMin), ConvertToLevel(options.ConsoleLogLevelMax), consoleLog); } N.LogManager.Configuration = config; } }
private static void Main(string[] args) { if (!File.Exists("config.json")) { Console.WriteLine("Couldn't find config.json. Please create it"); return; } NLog.Config.ConfigurationItemFactory.Default.Targets.RegisterDefinition("DiscordChannel", typeof(DiscordChannelTarget)); var config = new NLog.Config.LoggingConfiguration(); var logFile = new NLog.Targets.FileTarget("logfile") { FileName = "output.log" }; var logConsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logConsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logFile); // Apply config LogManager.Configuration = config; var json = File.ReadAllText("config.json"); var options = JsonConvert.DeserializeObject <Options>(json); DiscordBot = new Bot(); DiscordBot.RunAsync(options).GetAwaiter().GetResult(); }
private static Logger InitializeNlog_V3() { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "${basedir}/logs/Nlog.${shortdate}.log", Layout = "${longdate} ${logger} ${uppercase:${level}} ${message}", Encoding = Encoding.UTF8 }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole") { Layout = "${longdate} ${logger} ${uppercase:${level}} ${message}" }; // Rules for mapping loggers to targets config.AddRule(LogLevel.Trace, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile); // Apply config LogManager.Configuration = config; Logger nlogLogger = NLog.Web.NLogBuilder.ConfigureNLog(LogManager.Configuration).GetCurrentClassLogger(); return(nlogLogger); }
// ^ // NLOG public void ImplementLogging() { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config; NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger(); try { Logger.Info("Hello world"); System.Console.ReadKey(); } catch (Exception ex) { Logger.Error(ex, "Goodbye cruel world"); } }
private void SetLoggingPreferences() { var config = new NLog.Config.LoggingConfiguration(); var console = new NLog.Targets.ConsoleTarget("logconsole"); // Keep loglevel off by default. NLog.LogLevel minLogLevel; // If both Debug and Verbose are passed, Debug takes priority as NLog.Debug loglevel ranks lower than NLog.Info. // We will display all the log levels in between NLOG.Debug to NLog.Fatal(includes NLog.Info). if (MyInvocation.BoundParameters.ContainsKey("Debug")) { minLogLevel = NLog.LogLevel.Debug; } else if (MyInvocation.BoundParameters.ContainsKey("Verbose")) { minLogLevel = NLog.LogLevel.Info; } else { minLogLevel = NLog.LogLevel.Off; } config.AddRule(minLogLevel, NLog.LogLevel.Fatal, console); NLog.LogManager.Configuration = config; }
public void Init() { File.Delete(_path); ComponentRegistration.Reset(); ComponentRegistration.RegisterComponent <ILogger>(TYPE_LOGGER); ComponentRegistration.RegisterModulesFromAssembly(new ThirdPartyAutofacConfiguration() { AssemblyName = "Autofac.Extras.NLog", RegisterAll = true }); ComponentRegistration.Build(); var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget() { FileName = _path, Name = "logfile" }; var logconsole = new NLog.Targets.ConsoleTarget() { Name = "logconsole" }; config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Info, logconsole)); config.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Debug, logfile)); LogManager.Configuration = config; }
static void PrepareLoggers() { // Step 1. Create configuration object var config = new NLog.Config.LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var file = new NLog.Targets.FileTarget("FileLogger"); config.AddTarget(file); // Step 3. Set target properties file.ArchiveEvery = NLog.Targets.FileArchivePeriod.Day; file.ArchiveNumbering = NLog.Targets.ArchiveNumberingMode.DateAndSequence; file.ArchiveOldFileOnStartup = true; file.Layout = @"${date:universalTime=true:format=yyyy-MM-ddTHH\:mm\:ss.fffZ}|${level:uppercase=true}|${logger} ${event-properties:item=logSource}|${message}"; file.LineEnding = NLog.Targets.LineEndingMode.LF; file.FileName = "mpm.log"; var console = new NLog.Targets.ConsoleTarget("console"); config.AddTarget(console); console.Layout = @"[${date:universalTime=false:format=yyyy-MM-ddTHH\:mm\:ss.fffzzz}][${level:uppercase=true}][${logger}]: ${message}"; // Step 4. Define rules config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, file)); config.LoggingRules.Add(new NLog.Config.LoggingRule("*", NLog.LogLevel.Info, console)); NLog.LogManager.Configuration = config; }
public static void Main(string[] args) { string logFileLocation = PathProvider.GetApplicationDataFolder() + "/gatekeeper-logs.txt"; NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); NLog.Targets.FileTarget logFileTarget = new NLog.Targets.FileTarget("logfile") { FileName = logFileLocation }; NLog.Targets.ConsoleTarget logConsoleTarget = new NLog.Targets.ConsoleTarget("logconsole"); logFileTarget.Layout = "${longdate} ${message} ${exception:format=tostring}"; logConsoleTarget.Layout = "${longdate} ${message} ${exception:format=tostring}"; config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logConsoleTarget); config.AddRule(NLog.LogLevel.Error, NLog.LogLevel.Fatal, logFileTarget); NLog.Logger logger = NLogBuilder.ConfigureNLog(config).GetCurrentClassLogger(); try { logger.Debug("init main"); CreateHostBuilder(args).Build().Run(); } catch (Exception exception) { //NLog: catch setup errors logger.Error(exception, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } }
/// <summary> /// The main entry point for the application. /// </summary> static void Main() { var config = new NLog.Config.LoggingConfiguration(); string filename = DateTime.Now.ToString().Replace("/", "-").Replace(":", "-"); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = filename + ".txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); // Apply config NLog.LogManager.Configuration = config; Logger.Info("Iniciou"); ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new Service1() }; ServiceBase.Run(ServicesToRun); }
public override void Load() { //Create bindings Rebind<IStartupService>().To<StartupService>().InSingletonScope(); Rebind<IChunk>().To<Chunk>(); Rebind<INetworkPeer>().To<NetworkPeer>().InSingletonScope(); string path = Application.ExecutablePath.Substring(0, Application.ExecutablePath.Length - Path.GetFileName(Application.ExecutablePath).Length); Rebind<IFileSystem>().To<StandardFileSystem>().InSingletonScope().WithConstructorArgument("workingDirectory", new FileReference(path + "assets/")); Rebind<NetPeerConfiguration>().ToMethod(context => Kernel.Get<NetworkConfig>().CreateNetPeerConfig()).InSingletonScope(); Rebind<IConfigManager>().To<ConfigManager>().InSingletonScope().WithConstructorArgument("fileReference", new FileReference(Application.ExecutablePath).GetFileName() + "_config.json"); Rebind<ActorProvider>().To<ActorProvider>().InSingletonScope(); Rebind<IActor>().ToProvider<ActorProvider>(); //Logging config stuff { NLog.Config.LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); //targets NLog.Targets.FileTarget fileTarget = new NLog.Targets.FileTarget(); config.AddTarget("file", fileTarget); NLog.Targets.ConsoleTarget consoleTarget = new NLog.Targets.ConsoleTarget(); config.AddTarget("console", fileTarget); fileTarget.FileName = "${basedir}/${processname}_Log.txt"; fileTarget.Layout = "[${longdate}] [${level}] [${message}]"; consoleTarget.Layout = ">> [${date:format=HH\\:MM\\:ss}] [${level}] [${message}]"; //rules NLog.Config.LoggingRule loggingRule; loggingRule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, fileTarget); config.LoggingRules.Add(loggingRule); loggingRule = new NLog.Config.LoggingRule("*", NLog.LogLevel.Debug, consoleTarget); config.LoggingRules.Add(loggingRule); //activate NLog.LogManager.Configuration = config; } //Register services - Order is important services bound first get to register for events first and consequently receive events first. IStartupService startup = Kernel.Get<IStartupService>(); startup.RegisterStartupType<IConfigManager>(); startup.RegisterStartupType<IMessageTypeManager>(); startup.RegisterStartupType<IBlockManager>(); startup.RegisterStartupType<IMap>(); }