/// <summary> /// Skapar och returnerar en logger, /// om det redan har skapats en logger tidigare så returneras den existerande. /// </summary> /// <returns>PersonsokLogger</returns> public static PersonsokLogger CreatePersonsokLogger() { LoggingConfiguration logConfig = new NLog.Config.LoggingConfiguration(); FileTarget logfile = new NLog.Targets.FileTarget("logfile") { FileName = "personsok.log" }; ConsoleTarget logconsole = new NLog.Targets.ConsoleTarget("logconsole"); logConfig.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole); logConfig.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, logfile); NLog.LogManager.Configuration = logConfig; IConfigurationRoot rootConfig = new ConfigurationBuilder() .SetBasePath(System.IO.Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); IServiceProvider serviceProvider = new ServiceCollection() .AddTransient <PersonsokLogger>() .AddLogging(loggingBuilder => { loggingBuilder.ClearProviders(); loggingBuilder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); loggingBuilder.AddNLog(rootConfig); }) .BuildServiceProvider(); return(serviceProvider.GetRequiredService <PersonsokLogger>()); }
private void BuildNlogConfig() { LoggingConfiguration config = new LoggingConfiguration(); // Create targets ConsoleTarget consoleTarget = new ConsoleTarget(); config.AddTarget("console", consoleTarget); FileTarget fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); //memoryTarget = new MemoryTarget(); //config.AddTarget("memory", memoryTarget); // define layout consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${level} ${logger} ${message}"; fileTarget.FileName = System.IO.Path.Combine(System.IO.Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), "monotorrent"), "monotorrent.log"); fileTarget.Layout = "${level} ${stacktrace} ${message}"; //memoryTarget.Layout = "${date:format=HH\\:MM\\:ss} ${level} ${logger} ${message}"; // define rules LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule1); LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget); config.LoggingRules.Add(rule2); //LoggingRule rule3 = new LoggingRule("*", LogLevel.Debug, fileTarget); //config.LoggingRules.Add(rule3); LogManager.Configuration = config; }
public static LoggingConfiguration GetNLogConfig() { _config = new LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "/home/jol/logs/evo-demo-${shortdate}.log", Layout = "${longdate} [${uppercase:${level}}] ${event-properties:item=EventId.Id}${newline}位置:${callsite:className=True:methodName=True:fileName=True:includeSourcePath=True:skipFrames=1}${newline}${message}${newline}${exception}${newline}", ArchiveAboveSize = 10485760, ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, ConcurrentWrites = true, MaxArchiveFiles = 100000, KeepFileOpen = false, }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole") { Layout = "${longdate} [${uppercase:${level}}] ${event-properties:item=EventId.Id}${newline}位置:${callsite:className=True:methodName=True:fileName=True:includeSourcePath=True:skipFrames=1}${newline}${message}${newline}${exception}${newline}" }; // Rules for mapping loggers to targets _config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Fatal, logconsole); _config.AddRule(NLog.LogLevel.Trace, NLog.LogLevel.Debug, logfile); return(_config); }
public static void TargetConsole(bool verbose) { var target = new ConsoleTarget { Layout = LayoutFormat }; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, verbose ? LogLevel.Debug : LogLevel.Fatal); LogManager.ReconfigExistingLoggers(); }
public static void ConfigureViaCode(LogLevel consoleLogLevel, LogLevel fileLogLevel) { // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var consoleTarget = new ConsoleTarget(); config.AddTarget("console", consoleTarget); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); // Step 3. Set target properties consoleTarget.Layout = @"${message} ${onexception:EXCEPTION\:${exception:format=tostring}}"; fileTarget.Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} [${level:uppercase=true}] ${message} ${onexception:EXCEPTION\:${exception:format=tostring}}"; fileTarget.FileName = "C:\\temp\\logs\\SpiderOpenQuant.${date:format=yyyy-MM-dd hh}.log"; fileTarget.ConcurrentWrites = false; fileTarget.KeepFileOpen = true; fileTarget.OpenFileCacheTimeout = 60; // Step 4. Define rules var rule1 = new LoggingRule("*", consoleLogLevel, consoleTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("*", fileLogLevel, fileTarget); config.LoggingRules.Add(rule2); // Step 5. Activate the configuration LogManager.Configuration = config; }
public Form1() { InitializeComponent(); MetaTypeSet.EventError += MetaTypeSet_EventError; // подписываемся на событие EventError. Если оно произойдет, то запустить метод (Analyze_EventError). Tree.EventError += Tree_EventError; #region Logs var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "log_file.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); NLog.LogManager.Configuration = config; log = LogManager.GetCurrentClassLogger(); #endregion }
public IntegrationTestBase() { new StartupContext(); LogManager.Configuration = new LoggingConfiguration(); var consoleTarget = new ConsoleTarget { Layout = "${level}: ${message} ${exception}" }; LogManager.Configuration.AddTarget(consoleTarget.GetType().Name, consoleTarget); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, consoleTarget)); }
static Logger() { _verboseLogger = LogManager.GetLogger("TestR"); _benchmarkLogger = LogManager.GetLogger("TestR.Benchmark"); _consoleTarget = new ConsoleTarget(); _consoleTarget.Layout = "${longdate} ${message}"; _enableBenchmarking = false; _enableTracing = false; }
public static void ConfigureForConsoleLogging(LogLevel minLevel) { ConsoleTarget consoleTarget = new ConsoleTarget(); LoggingConfiguration config = new LoggingConfiguration(); LoggingRule rule = new LoggingRule("*", minLevel, consoleTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; }
private static void RegisterConsoleLogger(LogLevel minLevel, string loggerNamePattern = "*") { var consoleTarget = new ConsoleTarget(); consoleTarget.Layout = "${level}: ${message} ${exception:format=tostring}"; LogManager.Configuration.AddTarget(consoleTarget.GetType().Name, consoleTarget); LogManager.Configuration.LoggingRules.Add(new LoggingRule(loggerNamePattern, minLevel, consoleTarget)); LogManager.ConfigurationReloaded += (sender, args) => RegisterConsoleLogger(minLevel, loggerNamePattern); }
static void Main(string[] args) { ConsoleTarget target = new ConsoleTarget(); target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug); Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); }
public BaseTest() { ConsoleTarget target = new ConsoleTarget(); target.Layout = "${time}|${level:uppercase=true}|${callsite:className=true:includeSourcePath=false:methodName=false}|${message}"; SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace); Logger logger = LogManager.GetLogger("ee"); logger.Debug("another log message"); }
/** * Configures the Console/File logging. * * TODO: make it configurable (log levels, file name). */ public static void ConfigureLogging() { var config = new NLog.Config.LoggingConfiguration(); var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "app.log" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); NLog.LogManager.Configuration = config; }
public DependenciesConfiguration() { LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); FileTarget logfile = new NLog.Targets.FileTarget("logfile") { FileName = "debugOutput.txt" }; ConsoleTarget logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile); NLog.LogManager.Configuration = config; }
static async Task Start() { Console.Title = "Samples.SampleWithClean"; #region ConfigureNLog ConfigurationItemFactory.Default.LayoutRenderers .RegisterDefinition("customexception", typeof(CustomExceptionLayoutRenderer)); LoggingConfiguration config = new LoggingConfiguration(); string layout = "$|${logger}|${message}${onexception:${newline}${customexception:format=tostring}}"; ConsoleTarget consoleTarget = new ConsoleTarget { Layout = layout }; config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget)); FileTarget fileTarget = new FileTarget { FileName = "log.txt", Layout = layout }; config.AddTarget("file", fileTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget)); LogManager.Configuration = config; NServiceBus.Logging.LogManager.Use<NLogFactory>(); EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.SampleWithClean"); #endregion endpointConfiguration.UseSerialization<JsonSerializer>(); endpointConfiguration.UsePersistence<InMemoryPersistence>(); endpointConfiguration.EnableInstallers(); #region disable-retries endpointConfiguration.DisableFeature<FirstLevelRetries>(); endpointConfiguration.DisableFeature<SecondLevelRetries>(); endpointConfiguration.SendFailedMessagesTo("error"); #endregion IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration); try { await Run(endpoint); } finally { await endpoint.Stop(); } }
public static void ToConsole(string layout) { var consoleTarget = new ConsoleTarget { Layout = layout }; var config = new LoggingConfiguration(); config.AddTarget("console", consoleTarget); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget)); LogManager.Configuration = config; }
private void EnableCustomLogger() { // Make WebUtils log to Console as well as to Memory LoggingConfiguration logConf = new LoggingConfiguration(); this.memoryTarget = new MemoryTarget(); ConsoleTarget consoleTarget = new ConsoleTarget(); logConf.AddTarget("MemoryTarget", memoryTarget); logConf.AddTarget("ConsoleTarget", consoleTarget); logConf.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, memoryTarget)); logConf.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget)); LogManager.Configuration = logConf; WebUtils.logger = LogManager.GetLogger("TestLogger"); }
public static LoggingConfiguration ToConsole(LogLevel level) { const string Layout = @"${date:universalTime=true:format=yyyy-MM-ddTHH\:mm\:ss.fffZ} ${pad:padding=5:inner=${level:uppercase=true}} [${threadname}#${threadid}] - ${callsite:className=false:fileName=true:includeSourcePath=false:methodName=false:cleanNamesOfAnonymousDelegates=true} ${message}"; var consoleTarget = new ConsoleTarget { Name = "console", Layout = Layout }; var config = new LoggingConfiguration(); config.AddTarget(consoleTarget); config.LoggingRules.Add(new LoggingRule("*", level, consoleTarget)); return config; }
protected static void InitLogging() { new StartupContext(); TestLogger = LogManager.GetLogger("TestLogger"); if (LogManager.Configuration == null || LogManager.Configuration is XmlLoggingConfiguration) { LogManager.Configuration = new LoggingConfiguration(); var consoleTarget = new ConsoleTarget { Layout = "${level}: ${message} ${exception}" }; LogManager.Configuration.AddTarget(consoleTarget.GetType().Name, consoleTarget); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget)); RegisterExceptionVerification(); } }
protected static void InitLogging() { new StartupContext(); if (LogManager.Configuration == null || LogManager.Configuration.AllTargets.None(c => c is ExceptionVerification)) { LogManager.Configuration = new LoggingConfiguration(); var consoleTarget = new ConsoleTarget { Layout = "${level}: ${message} ${exception}" }; LogManager.Configuration.AddTarget(consoleTarget.GetType().Name, consoleTarget); LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, consoleTarget)); RegisterExceptionVerification(); LogManager.ReconfigExistingLoggers(); } }
public static void EnableDebugConsoleOutput() { if (IsDebugConsoleOutputEnabled) { return; } LoggingConfiguration config = LogManager.Configuration; ConsoleTarget consoleTarget = new ConsoleTarget() { Name = "consoleDebugOutput" }; LoggingRule consoleRule = new LoggingRule("*", consoleTarget); consoleRule.EnableLoggingForLevel(LogLevel.Trace); consoleRule.EnableLoggingForLevel(LogLevel.Debug); config.AddTarget(consoleTarget); config.LoggingRules.Add(consoleRule); IsDebugConsoleOutputEnabled = true; }
private static void ConfigureLogging() { // If there is a configuration file then this will already be set if (LogManager.Configuration != null) { return; } var config = new NLog.Config.LoggingConfiguration(); var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); logconsole.Layout = "${longdate}|${level:uppercase=true}|${message}"; config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); LogManager.Configuration = config; }
/* función estática InitLogger() => void * Inicializa el servicio de logging de la aplicación */ public static void InitLogger() { LoggingConfiguration config = new NLog.Config.LoggingConfiguration(); // Establece las salidas de logging a consola y archivo Target logconsole = new NLog.Targets.ConsoleTarget("logconsole"); Target logfile = new NLog.Targets.FileTarget("logfile") { FileName = "nlog.log" }; // Añade las reglas de configuración con los umbrales de los niveles de seguridad config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole); config.AddRule(LogLevel.Info, LogLevel.Fatal, logfile); // Aplica la configuración NLog.LogManager.Configuration = config; }
public void TestFixtureSetUp() { var config = new LoggingConfiguration(); _logTarget = new MemoryTarget(); _logTarget.Layout = "${level:uppercase=true}|${message}|${exception:format=tostring}"; config.AddTarget("memory", _logTarget); var consoleTarget = new ConsoleTarget(); consoleTarget.Layout = "${longdate}|${logger}|${level:uppercase=true}|${message}|${exception:format=tostring}"; config.AddTarget("console", consoleTarget); var rule = new LoggingRule("*", LogLevel.Trace, _logTarget); rule.Targets.Add(consoleTarget); config.LoggingRules.Add(rule); LogManager.Configuration = config; }
private static void ConfigureLogger(ActionType action, IKernel kernel) { string logRoot = Path.Combine( AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "Log", DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + action ); ProgramSettings settings = kernel.Get<ProgramSettings>(); string layout = "${longdate}|${level}|${logger}|${message}${onexception:inner=${newline}}${exception:format=tostring}"; LoggingConfiguration config = new LoggingConfiguration(); ConsoleTarget console = new ConsoleTarget(); config.AddTarget("console", console); FileTarget file = new FileTarget(); config.AddTarget("file", file); FileTarget debug = new FileTarget(); config.AddTarget("debug", debug); FileTarget trace = new FileTarget(); config.AddTarget("trace", trace); FileTarget error = new FileTarget(); config.AddTarget("error", error); console.Layout = settings.Debug ? "${longdate}|${level}|${logger}|${message}" : layout; file.FileName = logRoot + "/log.txt"; file.Encoding = Encoding.UTF8; file.Layout = layout; debug.FileName = logRoot + "/debug.txt"; debug.Encoding = Encoding.UTF8; debug.Layout = layout; trace.FileName = logRoot + "/verbose.txt"; trace.Encoding = Encoding.UTF8; trace.Layout = layout; error.FileName = logRoot + "/error.txt"; error.Encoding = Encoding.UTF8; error.Layout = layout; config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, console)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, file)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, debug)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, trace)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Error, error)); LogManager.Configuration = config; }
public static void RegisterConsoleLogger(LogLevel minLevel, string loggerNamePattern = "*") { try { var consoleTarget = new ConsoleTarget(); consoleTarget.Layout = "${message} ${exception}"; LogManager.Configuration.AddTarget(consoleTarget.GetType().Name, consoleTarget); LogManager.Configuration.LoggingRules.Add(new LoggingRule(loggerNamePattern, minLevel, consoleTarget)); LogManager.ConfigurationReloaded += (sender, args) => RegisterConsoleLogger(minLevel, loggerNamePattern); } catch (Exception e) { Console.WriteLine(e); if (LogManager.ThrowExceptions) throw; } }
public LoggerService() { //TODO move this to configuration var pathToLog = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), @"Expances\Log\"); if (!Directory.Exists(pathToLog)) { Directory.CreateDirectory(pathToLog); } var config = new LoggingConfiguration(); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); fileTarget.FileName = $"{pathToLog}/{"${shortdate}.log"}"; fileTarget.Layout = "${level}|${date}|${machinename}|${windows-identity} ${message}"; var consoleTarget = new ConsoleTarget { Name = "String", Layout = "${message}" }; config.AddTarget(consoleTarget); #if DEBUG config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); #else config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget)); #endif LogManager.Configuration = config; _log = LogManager.GetCurrentClassLogger(); //Info("Current directory: {0}", Environment.CurrentDirectory); }
public void ConsoleOutTest() { var target = new ConsoleTarget() { Header = "-- header --", Layout = "${logger} ${message}", Footer = "-- footer --", }; var consoleOutWriter = new StringWriter(); TextWriter oldConsoleOutWriter = Console.Out; Console.SetOut(consoleOutWriter); try { var exceptions = new List<Exception>(); target.Initialize(null); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message1").WithContinuation(exceptions.Add)); target.WriteAsyncLogEvent(new LogEventInfo(LogLevel.Info, "Logger1", "message2").WithContinuation(exceptions.Add)); target.WriteAsyncLogEvents( new LogEventInfo(LogLevel.Info, "Logger1", "message3").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "message4").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "message5").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "message6").WithContinuation(exceptions.Add)); Assert.AreEqual(6, exceptions.Count); target.Close(); } finally { Console.SetOut(oldConsoleOutWriter); } string expectedResult = @"-- header -- Logger1 message1 Logger1 message2 Logger1 message3 Logger2 message4 Logger2 message5 Logger1 message6 -- footer -- "; Assert.AreEqual(expectedResult, consoleOutWriter.ToString()); }
/// <summary> /// Initialise a new instance of the NLogLogger using a default configuration. /// </summary> public NLogLogger() { LoggingConfiguration logConfig = new LoggingConfiguration(); FileTarget fileTarget = new FileTarget(); fileTarget.FileName = "${basedir}/ExamplesConsoleLog_" + NetworkComms.NetworkIdentifier + ".txt"; fileTarget.Layout = "${date:format=HH\\:mm\\:ss\\:fff} [${threadid} - ${level}] - ${message}"; ConsoleTarget consoleTarget = new ConsoleTarget(); consoleTarget.Layout = "${date:format=HH\\:mm\\:ss} - ${message}"; logConfig.AddTarget("file", fileTarget); logConfig.AddTarget("console", consoleTarget); logConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, fileTarget)); logConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); LogManager.Configuration = logConfig; logger = LogManager.GetCurrentClassLogger(); LogManager.EnableLogging(); }
public static void Start() { Kick.Start(c => c .IncludeAssemblyFor<Project>() .IncludeAssemblyFor<ProjectRepository>() .UseNLog(config => { var consoleTarget = new ConsoleTarget(); consoleTarget.Layout = "${time} ${level:uppercase=true:padding=1:fixedLength=true} ${logger:shortName=true} ${message} ${exception:format=tostring}"; config.AddTarget("console", consoleTarget); var consoleRule = new LoggingRule("*", NLog.LogLevel.Trace, consoleTarget); config.LoggingRules.Add(consoleRule); }) .UseAutofac() .UseMongoDB() .UseStartupTask() ); }
private void SetUpNLog() { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "backupclientlogfile_helperservice.txt" }; var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); // Rules for mapping loggers to targets config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logconsole); config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Fatal, logfile); // Apply config LogManager.Configuration = config; _logger = LogManager.GetCurrentClassLogger(); }
private void Configure() { if (verbose <= 0) { return; } var level = verbose >= 2 ? LogLevel.Debug : LogLevel.Warn; var config = new LoggingConfiguration(); var target = new ConsoleTarget { Layout = @"${message}${onexception:${newline}EXCEPTION OCCURRED\: ${exception:format=tostring}}" }; var rule = new LoggingRule("*", level, target); config.LoggingRules.Add(rule); config.AddTarget("console", target); LogManager.Configuration = config; }
static Log() { CurrentLogDirectory = Path.Combine(DataLocation.DataDirectory(), DirectoryName, Constant.Version); if (!Directory.Exists(CurrentLogDirectory)) { Directory.CreateDirectory(CurrentLogDirectory); } var configuration = new LoggingConfiguration(); var fileTarget = new FileTarget() { FileName = CurrentLogDirectory.Replace(@"\", "/") + "/${shortdate}.txt", }; var consoleTarget = new NLog.Targets.ConsoleTarget(); #if DEBUG configuration.AddRule(LogLevel.Debug, LogLevel.Fatal, fileTarget); #else configuration.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget); #endif LogManager.Configuration = configuration; }
// DiscordSocketClient and CommandService are injected automatically from the IServiceProvider public LoggingService(DiscordSocketClient discord, CommandService commands) { _logDirectory = Path.Combine(AppContext.BaseDirectory, "logs"); _discord = discord; _commands = commands; _discord.Log += OnLogAsync; _commands.Log += OnLogAsync; var logConfig = new NLog.Config.LoggingConfiguration(); var logFile = new NLog.Targets.FileTarget("logFile") { FileName = _logFile, ArchiveEvery = FileArchivePeriod.Day }; var logConsole = new NLog.Targets.ConsoleTarget("logConsole"); logConfig.AddRule(LogLevel.Info, LogLevel.Fatal, logFile); logConfig.AddRule(LogLevel.Info, LogLevel.Fatal, logConsole); NLog.LogManager.Configuration = logConfig; }
public MainWindow() { InitializeComponent(); //Sets default properties rows from project settings settingshandler = new SettingsHandler(sp_settings); #region logger init 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)); NLog.LogManager.Configuration = config; //Logger logger = NLog.LogManager.GetCurrentClassLogger(); #endregion logger.Info("start"); //checking net status indikacenetu(); Connection.CheckingConnection(); GetterInit(settingshandler.getUrlTB()); //int Desc; //if (!InternetGetConnectedState(out Desc, 0)) // lb_status.Content = "No connection"; }
static void Main(string[] args) { var config = new NLog.Config.LoggingConfiguration(); 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.Error, logconsole)); LogManager.Configuration = config; var currentDir = ConfigurationManager.AppSettings["LogFileDir"]; var conf = new LoggingConfiguration(); var fileTarget = new FileTarget { Name = "Default", FileName = Path.Combine(currentDir, "log.txt"), Layout = "${date} ${message} ${onexception:inner=${exception:format=toString}}" }; conf.AddTarget(fileTarget); conf.AddRuleForAllLevels(fileTarget); var logFactory = new LogFactory(conf); var container = AutofacConfig.GetContainer(); var scannerService = container.Resolve <IProcessScannedFiles>(); HostFactory.Run( hostConf => hostConf.Service <IProcessScannedFiles>( s => { s.ConstructUsing(() => scannerService); s.WhenStarted(serv => serv.Start()); s.WhenStopped(serv => serv.Stop()); } ).UseNLog(logFactory)); }
public static void Main(string[] args) { Console.Title = "Theseus platform"; //Logging configuration // Step 1. Create configuration object var config = new LoggingConfiguration(); // Step 2. Create targets and add them to the configuration var consoleTarget = new ConsoleTarget(); config.AddTarget("console", consoleTarget); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); // Step 3. Set target properties consoleTarget.Layout = @"[${date:format=HH\:mm\:ss.fff}][${logger}.${level}]: ${message} ${exception:format=Message,StackTrace}"; fileTarget.FileName = "${basedir}/logs/${date:format=yyyy.MM.dd}.txt"; fileTarget.Layout = @"[${date:format=dd.MM.yyyy HH\:mm\:ss.fff}][${logger}.${level}]: ${message} ${exception:format=Message,StackTrace}"; fileTarget.DeleteOldFileOnStartup = false; fileTarget.AutoFlush = true; // Step 4. Define rules var rule1 = new LoggingRule("*", LogLevel.Info, consoleTarget); config.LoggingRules.Add(rule1); var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget); config.LoggingRules.Add(rule2); // Step 5. Activate the configuration LogManager.Configuration = config; var core = new Theseus.Core("configuration.json", "accounts.json"); core.Start(); core.Wait(); }
private static LoggingConfiguration ConfigureLogger() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget { Name = "logFile", FileName = @"\\Storage1\Users\garmstrong\RenameLogs\SimpleLog.txt", Layout = "[${level}] ${message}", KeepFileOpen = true, //DeleteOldFileOnStartup = true, }; var consoleTarget = new ConsoleTarget {Name = "logConsole"}; var fileRule = new LoggingRule("logFile", LogLevel.Debug, fileTarget); var consoleRule = new LoggingRule("logConsole", LogLevel.Debug, consoleTarget); config.AddTarget(fileTarget); config.AddTarget(consoleTarget); config.LoggingRules.Add(fileRule); config.LoggingRules.Add(consoleRule); return config; }
protected virtual void SetupLogging() { var config = new LoggingConfiguration(); var consoleTarget = new ConsoleTarget(); consoleTarget.Layout = @"${message}"; config.AddTarget("console", consoleTarget); var rule = new LoggingRule("*", NLog.LogLevel.Debug, consoleTarget); config.LoggingRules.Add(rule); NLog.LogManager.Configuration = config; if (!_loggingSetUp) { NpgsqlLogManager.Provider = new NLogLoggingProvider(); _loggingSetUp = true; } }
public static void ConfigureNLog() { try { var config = new NLog.Config.LoggingConfiguration(); var minLogLevel = LogLevel.FromString(Environment.GetEnvironmentVariable("LOGGING_MIN_LEVEL")); var maxLogLevel = LogLevel.FromString(Environment.GetEnvironmentVariable("LOGGING_MAX_LEVEL")); //console logging var logconsole = new NLog.Targets.ConsoleTarget("logconsole"); config.AddRule(minLogLevel, maxLogLevel, logconsole); if (Globals.EnableFileLogging) { // file loggin var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "logfile.log" }; config.AddRule(minLogLevel, maxLogLevel, logfile); } if (Globals.EnableDBLogging) { //db loggin var logdb = new NLog.Targets.DatabaseTarget("logdb"); logdb.CommandText = @" insert into [Log] (MachineName, Logged, Level, Message,Logger, Properties, Callsite, Exception) values (@MachineName, @Logged, @Level, @Message, @Logger, @Properties, @Callsite, @Exception);"; logdb.CommandType = System.Data.CommandType.Text; logdb.ConnectionString = Globals.SkillbaseConnectionString; logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@MachineName", Layout = "${machinename}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Logged", Layout = "${date}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Level", Layout = "${level}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Message", Layout = "${message}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Logger", Layout = "${logger}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Properties", Layout = "${all-event-properties:separator=|}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Callsite", Layout = "${callsite}" }); logdb.Parameters.Add(new DatabaseParameterInfo() { Name = "@Exception", Layout = "${exception:tostring}" }); config.AddRule(minLogLevel, maxLogLevel, logdb); } // Apply config NLog.LogManager.Configuration = config; } catch (Exception) { } }
public NLogger(LogOptions options = null) { options = options ?? new LogOptions { EnableConsoleLog = true }; var config = new NLog.Config.LoggingConfiguration(); if (options.EnableFileLog) { var fileConf = new NLog.Targets.FileTarget("jimuLogFile") { FileName = ".\\log\\${level:lowercase=true}\\${shortdate}.log", ArchiveAboveSize = 10000000, Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level:uppercase=true} ${message}" }; if ((options.FileLogLevel & LogLevel.Error) == LogLevel.Error) { config.AddRuleForOneLevel(NLog.LogLevel.Error, fileConf); } if ((options.FileLogLevel & LogLevel.Warn) == LogLevel.Warn) { //config.AddRuleForOneLevel(NLog.LogLevel.Warn, fileConf); config.AddRule(NLog.LogLevel.Warn, NLog.LogLevel.Error, fileConf); } if ((options.FileLogLevel & LogLevel.Info) == LogLevel.Info) { config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Error, fileConf); //config.AddRuleForOneLevel(NLog.LogLevel.Info, fileConf); } if ((options.FileLogLevel & LogLevel.Debug) == LogLevel.Debug) { config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Error, fileConf); //config.AddRuleForOneLevel(NLog.LogLevel.Debug, fileConf); } } if (options.EnableConsoleLog) { var consoleLog = new NLog.Targets.ConsoleTarget("jimuLogconsole") { Layout = @"${date:format=yyyy-MM-dd HH\:mm\:ss.fff} ${level:uppercase=true} ${message}" }; if ((options.ConsoleLogLevel & LogLevel.Error) == LogLevel.Error) { config.AddRuleForOneLevel(NLog.LogLevel.Error, consoleLog); } if ((options.ConsoleLogLevel & LogLevel.Warn) == LogLevel.Warn) { config.AddRule(NLog.LogLevel.Warn, NLog.LogLevel.Error, consoleLog); //config.AddRuleForOneLevel(NLog.LogLevel.Warn, consoleLog); } if ((options.ConsoleLogLevel & LogLevel.Info) == LogLevel.Info) { config.AddRule(NLog.LogLevel.Info, NLog.LogLevel.Error, consoleLog); //config.AddRuleForOneLevel(NLog.LogLevel.Info, consoleLog); } if ((options.ConsoleLogLevel & LogLevel.Debug) == LogLevel.Debug) { config.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Error, consoleLog); //config.AddRuleForOneLevel(NLog.LogLevel.Debug, consoleLog); } } NLog.LogManager.Configuration = config; _logger = NLog.LogManager.GetLogger("jimuLogger"); }
public void AddConsoleOutput() { RemoveTarget("ConsoleTargetWrapper"); var wrapper = new AsyncTargetWrapper (); wrapper.Name = "ConsoleTargetWrapper"; var target = new ConsoleTarget() { Layout = "${level}, ${logger}, ${message}", Error = false }; target.Name = "ConsoleTarget"; wrapper.WrappedTarget = target; AddLogTarget(wrapper, LogSeverity); }
public void SplitGroupToStringTest() { var myTarget1 = new MyTarget(); var myTarget2 = new FileTarget("file1"); var myTarget3 = new ConsoleTarget("Console2"); var wrapper = new SplitGroupTarget() { Targets = { myTarget1, myTarget2, myTarget3 }, }; Assert.Equal("SplitGroup Target[(unnamed)](MyTarget, File Target[file1], Console Target[Console2])", wrapper.ToString()); }
static void Main(string[] args) { ExitEvent = new ManualResetEvent(false); MigrateSettingsDirectory(); try { if (!Directory.Exists(AppConfigDirectory)) { IsFirstRun = true; Directory.CreateDirectory(AppConfigDirectory); } Console.WriteLine("App config/log directory: " + AppConfigDirectory); } catch (Exception ex) { MessageBox.Show("Could not create settings directory. " + ex.Message); Application.Exit(); return; } var logConfig = new LoggingConfiguration(); var logFile = new FileTarget(); logConfig.AddTarget("file", logFile); logFile.Layout = "${longdate} ${level} ${message} \n ${exception:format=ToString}\n"; logFile.FileName = Path.Combine(AppConfigDirectory, "log.txt"); logFile.ArchiveFileName = "log.{#####}.txt"; logFile.ArchiveAboveSize = 500000; logFile.MaxArchiveFiles = 1; logFile.KeepFileOpen = false; logFile.ArchiveNumbering = ArchiveNumberingMode.DateAndSequence; var logFileRule = new LoggingRule("*", LogLevel.Debug, logFile); logConfig.LoggingRules.Add(logFileRule); if (Program.IsWindows) { #if !__MonoCS__ var logAlert = new MessageBoxTarget(); logConfig.AddTarget("alert", logAlert); logAlert.Layout = "${message}"; logAlert.Caption = "Alert"; var logAlertRule = new LoggingRule("*", LogLevel.Fatal, logAlert); logConfig.LoggingRules.Add(logAlertRule); #endif } var logConsole = new ConsoleTarget(); logConfig.AddTarget("console", logConsole); logConsole.Layout = "${longdate} ${level} ${message} ${exception:format=ToString}"; var logConsoleRule = new LoggingRule("*", LogLevel.Debug, logConsole); logConfig.LoggingRules.Add(logConsoleRule); LogManager.Configuration = logConfig; LoggerInstance = LogManager.GetCurrentClassLogger(); ReadSettingsFile(); var serverTask = Task.Run(async () => { ServerInstance = new Server(); await ServerInstance.Start(); }); try { if (Program.IsWindows) { #if !__MonoCS__ Application.Run(new Main()); #endif } } catch (Exception) { } Console.WriteLine("Running in headless mode."); Task.WaitAll(serverTask); Console.WriteLine("Server thread exit"); }