public static void Main(string[] args) { GlobalDiagnosticsContext.Set("configDir", "C:\\git\\damienbod\\AspNetCoreNlog\\Logs"); GlobalDiagnosticsContext.Set("connectionString", "Data Source=N051\\MSSQLSERVER2014;Initial Catalog=Nlogs;Integrated Security=True;"); // GlobalDiagnosticsContext.Set("connectionString", Configuration.GetConnectionString("NLogDb")); var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { //logger.Debug("init main"); BuildWebHost(args).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(); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } GlobalDiagnosticsContext.Set("nlogDbConnection", Configuration.GetConnectionString("DefaultConnection")); GlobalDiagnosticsContext.Set("appName", Configuration["AppName"]); loggerFactory.AddNLog(); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
public void GDCTest1() { GlobalDiagnosticsContext.Clear(); Assert.False(GlobalDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, GlobalDiagnosticsContext.Get("foo")); Assert.False(GlobalDiagnosticsContext.Contains("foo2")); Assert.Equal(string.Empty, GlobalDiagnosticsContext.Get("foo2")); Assert.Equal(0, GlobalDiagnosticsContext.GetNames().Count); GlobalDiagnosticsContext.Set("foo", "bar"); GlobalDiagnosticsContext.Set("foo2", "bar2"); Assert.True(GlobalDiagnosticsContext.Contains("foo")); Assert.Equal("bar", GlobalDiagnosticsContext.Get("foo")); Assert.Equal(2, GlobalDiagnosticsContext.GetNames().Count); GlobalDiagnosticsContext.Remove("foo"); Assert.False(GlobalDiagnosticsContext.Contains("foo")); Assert.Equal(string.Empty, GlobalDiagnosticsContext.Get("foo")); Assert.True(GlobalDiagnosticsContext.Contains("foo2")); Assert.Equal("bar2", GlobalDiagnosticsContext.Get("foo2")); Assert.Equal(1, GlobalDiagnosticsContext.GetNames().Count); Assert.Null(GlobalDiagnosticsContext.GetObject("foo3")); Assert.Equal(string.Empty, GlobalDiagnosticsContext.Get("foo3", null)); GlobalDiagnosticsContext.Set("foo3", new { One = 1 }); Assert.NotNull(GlobalDiagnosticsContext.Get("foo3", null)); }
public void LogRubberduckStart() { var version = _version.CurrentVersion; GlobalDiagnosticsContext.Set("RubberduckVersion", version.ToString()); var headers = new List <string> { $"\r\n\tRubberduck version {version} loading:", $"\tOperating System: {Environment.OSVersion.VersionString} {(Environment.Is64BitOperatingSystem ? "x64" : "x86")}" }; try { headers.AddRange(new [] { $"\tHost Product: {Application.ProductName} {(Environment.Is64BitProcess ? "x64" : "x86")}", $"\tHost Version: {Application.ProductVersion}", $"\tHost Executable: {_filesystem.Path.GetFileName(Application.ExecutablePath).ToUpper()}", // .ToUpper() used to convert ExceL.EXE -> EXCEL.EXE }); } catch { headers.Add("\tHost could not be determined."); } LogLevelHelper.SetDebugInfo(string.Join(Environment.NewLine, headers)); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMiddleware <ResponseLogMiddleware>(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } GlobalDiagnosticsContext.Set("connectionString", "Server=DVTL597LKC2;Initial Catalog=Logging;Integrated Security=True"); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseMvcWithDefaultRoute(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "apicore"); c.DocExpansion(DocExpansion.None); c.EnableFilter(); c.DisplayRequestDuration(); c.ShowExtensions(); c.OAuthClientId("mvc"); c.OAuthClientSecret("secret"); }); }
public static async Task Main(string[] args) { IConfigurationRoot config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true) .AddCommandLine(args) .Build(); _appSettings = config.Get <AppSettings>(); GlobalDiagnosticsContext.Set("connectionString", _appSettings.ConnectionStrings.ConnectionString); Logger logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { var host = CreateWebHostBuilder(args).Build(); await InitializeDatabaseAsync(host); CreateConfigLog(host); host.Run(); } catch (Exception ex) { logger.Error(ex, "ApplicationStopped"); } finally { LogManager.Shutdown(); } }
static Program() { GlobalDiagnosticsContext.Set( "assemblyVersion", Assembly.GetExecutingAssembly().GetName().Version.ToString()); Logger = LogManager.GetCurrentClassLogger(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } GlobalDiagnosticsContext.Set("connectionString", Configuration.GetConnectionString("BackendTestConnectionString")); loggerFactory.AddNLog(); app.UseCors("AllowAllOrigins"); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Backend Test API V1"); c.RoutePrefix = string.Empty; }); app.UseHttpsRedirection(); app.UseMvc(); //PopulateDatabase(); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseAuthentication(); app.MapWhen(context => { if (!context.Request.GetUri().ToString().EndsWith("/elmah")) { return(false); } var role = context.User.Claims.SingleOrDefault(x => x.Type == "Admin"); return(role == null); }, Handle); GlobalDiagnosticsContext.Set("connectionString", _configuration.GetConnectionString("DefaultConnection")); //loggerFactory.AddNLog(); app.UseElmah(); app.UseMvc(); }
protected override void OnStartup(StartupEventArgs e) { var uriSchemeInArgs = e.Args.Any(a => a.Contains(UriSchemeRegistration.UriScheme, StringComparison.OrdinalIgnoreCase)); GlobalDiagnosticsContext.Set("application", uriSchemeInArgs ? "invokedFromProtocol" : "default"); if (ShouldBeMinimized(e.Args)) { StartMinimized = true; Logger.Log(LogLevel.Info, "Minimized start requested."); } Logger.Log(LogLevel.Info, $"BuildNotifications started. Version {CurrentVersion()} Args: {string.Join(" ", e.Args)}"); if (IsInvokedFromDistributedNotification(e)) { WriteToastArgumentsToSharedMonitoredDirectory(e); if (OtherProcessIsRunning()) { Logger.Log(LogLevel.Info, "Shutting down application, as other instance is already running."); Shutdown(); return; } Logger.Log(LogLevel.Info, "No other instance is running. Continuing startup"); } else { Logger.Log(LogLevel.Info, "Instance was not started from URI protocol. Initializing normally."); } Logger.Log(LogLevel.Info, "Normal startup. Using MainWindow.xaml"); StartupUri = new Uri("MainWindow.xaml", UriKind.Relative); base.OnStartup(e); }
private void Application_Startup(object sender, StartupEventArgs e) { // Multiple istance check if (!e.Args.Contains("-m") && !e.Args.Contains("/m")) { Process proc = Process.GetCurrentProcess(); int count = Process.GetProcesses().Where(p => p.ProcessName == proc.ProcessName).Count(); if (count > 1) { Environment.Exit(1); return; } } // Upgrade Settings if (Settings.Default.UpgradeSettings) { Settings.Default.Upgrade(); Settings.Default.UpgradeSettings = false; Settings.Default.Save(); } GlobalDiagnosticsContext.Set("logDirectory", ApplicationSettings.Directories.Log); InitializeDirectoryTree(); InitializeDatabase(); ApplySkin(UserSettings.Themes.Skin); }
/// <summary> /// Метод выполняет базовую инициализаци службы /// в т.ч. добавление логгеров и подписку на необработанные исключения. /// </summary> /// <param name="serviceName">Имя службы.</param> protected void BasicInitialize(string serviceName) { // GlobalDiagnosticsContext.Set("service", _serviceName); GlobalDiagnosticsContext.Set("service", serviceName); _loggerFactory = new LoggerFactory(); _loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true, }); _cts = new CancellationTokenSource(); _logger = _loggerFactory.CreateLogger <IMicroserviceCore>(); // Добавить построитель конфигурации _configurationBuilder = new ConfigurationBuilder(); ServiceBackgroundThread = new Thread((arguments) => { var args = arguments as DoWorkArguments; DoWork.Invoke(args.ServiceProvider, args.CancellationToken); _logger.LogWarning($"Поток службы {ServiceIdentifier} прекратил работу, выполнение службы остановлено."); }); AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; _serviceCollection.AddSingleton((p) => _cts); _serviceCollection.AddSingleton(_loggerFactory); _serviceCollection.AddSingleton(typeof(ILogger <>), typeof(Logger <>)); _serviceCollection.AddLogging(x => x.SetMinimumLevel(LogLevel.Trace)); }
/// <summary> /// Logs the specified message and infers the severity of the log from the type of message that was /// also sent down to the consuming program (example: A message type of Info could log Info, but should /// never log an Error/Fatal). /// </summary> /// <param name="message">The message.</param> /// <param name="messageType">Type of the message.</param> /// <param name="referenceId">The reference identifier.</param> /// <param name="param">The optional parameters.</param> public virtual void Log(string message, MessageType messageType, Guid?referenceId, params object[] param) { if (referenceId.HasValue) { GlobalDiagnosticsContext.Set("ReferenceId", referenceId.ToString()); } else { GlobalDiagnosticsContext.Set("ReferenceId", null); } Severity s = Severity.Trace; switch (messageType) { case MessageType.Info: s = Severity.Info; break; case MessageType.Success: s = Severity.Debug; break; case MessageType.Warning: s = Severity.Warn; break; case MessageType.Error: s = Severity.Error; break; } this.Log(message, s, param); }
private async Task <bool> UserLogin(string email, string pass, User usr) { if (usr != null) { var bytepass = await CustomEncryptor.EncryptAsync(pass); var test = System.Text.Encoding.UTF8.GetString(bytepass); var usrpass = System.Text.Encoding.UTF8.GetString(usr.Password); if (usrpass == test) { GlobalDiagnosticsContext.Set("Email", usr.Email); Session["Username"] = usr.Username; Session["User"] = usr; logger.Info("Successful login, username:"******"Failed attempt to login:"******"Failed attempt to login:" + email); return(false); } }
public static void Main(string[] args) { var logDir = Microsoft.Azure.Web.DataProtection.Util.IsAzureEnvironment() ? $"{BaseDirectory}/data/logs" : $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}/CNCLib.Server/logs"; if (!Directory.Exists(logDir)) { Directory.CreateDirectory(logDir); } GlobalDiagnosticsContext.Set("logDir", logDir); var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); #if DEBUG LogManager.ThrowExceptions = true; #endif try { ProgramUtilities.StartWebService(args, CreateHostBuilder); } catch (Exception e) { logger.Error(e); throw; } }
// GET: Home public ActionResult Index() { GlobalDiagnosticsContext.Set("Application", "LoggerPerfTestWeb"); var sb = new StringBuilder(); var logger = LogManager.GetLogger("PerfTest"); //var logger = LogManager.GetLogger("PerfTestCrash"); var log4mb = System.IO.File.ReadAllText(Server.MapPath("~/bin/4MB.txt")); var nb4mb = 1000; long duration4mb; var sw = new Stopwatch(); sb.AppendLine($"Start {nb4mb} 4MB logs."); sw.Start(); for (int i = 0; i < nb4mb; i++) { logger.Info(log4mb); } sw.Stop(); duration4mb = sw.ElapsedMilliseconds; sb.AppendLine($"{nb4mb} 4MB logs in {duration4mb}ms."); var proc = Process.GetCurrentProcess(); sb.AppendLine($"PrivateMemorySize = {proc.PrivateMemorySize64}"); sb.AppendLine($"VirtualMemorySize = {proc.VirtualMemorySize64}"); sb.AppendLine($"PeakVirtualMemorySize = {proc.PeakVirtualMemorySize64}"); sb.AppendLine($"PagedMemorySize = {proc.PagedMemorySize64}"); sb.AppendLine($"PeakPagedMemorySize = {proc.PeakPagedMemorySize64}"); return(Content(sb.ToString())); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } GlobalDiagnosticsContext.Set("connectionString", Configuration.GetConnectionString("DefaultConnection")); loggerFactory.AddNLog(); app.UseElmah(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope()) { var context = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); context.Database.Migrate(); } }
private static IServiceProvider BuildDi() { var services = new ServiceCollection(); //Runner is the custom class services.AddTransient <Runner>(); services.AddSingleton <ILoggerFactory, LoggerFactory>(); services.AddSingleton(typeof(ILogger <>), typeof(Logger <>)); services.AddLogging((builder) => builder.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace)); var serviceProvider = services.BuildServiceProvider(); var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); //configure NLog loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true }); NLog.LogManager.LoadConfiguration("nlog.config"); GlobalDiagnosticsContext.Set("appName", "BasicConsole"); GlobalDiagnosticsContext.Set("cloud_RoleName", "Trading app"); return(serviceProvider); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // Сбои при входе не приводят к блокированию учетной записи // Чтобы ошибки при вводе пароля инициировали блокирование учетной записи, замените на shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: // Переменная для nlog'a GlobalDiagnosticsContext.Set("UserName", model.UserName); Logger.Info("Успешный вход в систему."); return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "Неудачная попытка входа."); return(View(model)); } }
public SAPPTcpClient() { ReadArgs(); iSettings.LoadSettings(); logger.Info("Settings loaded"); GlobalDiagnosticsContext.Set("ipport", iSettings.IP_Port.Split(':')[0]); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public async void Configure(IApplicationBuilder app, IWebHostEnvironment env) { GlobalDiagnosticsContext.Set("configDir", Directory.GetCurrentDirectory() + "\\Logs"); GlobalDiagnosticsContext.Set("connectionString", ConnectionStrings.LoggerConnection); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseCors(builder => builder.AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin()); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); await app.UseOcelot(); }
public static void Main(string[] args) { #if DEBUG LogManager.ThrowExceptions = true; #endif string localAppData; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { localAppData = "/var/log"; } else { localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (!Directory.Exists(localAppData) || RunsAsService()) { // service user localAppData = Environment.GetEnvironmentVariable("ProgramData"); } } GlobalDiagnosticsContext.Set("logDir", $"{localAppData}/CNCLib.Serial.Server/logs"); var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger(); try { logger.Info("Starting (Main)"); StartWebService(args); } catch (Exception e) { logger.Error(e); throw; } }
/// <summary> /// Renders the specified Global Diagnostics Context item and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { //don't use GlobalDiagnosticsContext.Get to ensure we are not locking the Factory (indirect by LogManager.Configuration). var o = GlobalDiagnosticsContext.GetObject(this.Item); builder.Append(o, logEvent, LoggingConfiguration); }
public static void Main(string[] args) { GlobalDiagnosticsContext.Set("configDir", "C:\\Logs"); GlobalDiagnosticsContext.Set("connectionString", "Server=GODYLA;Database=SiteKufar1;Trusted_Connection=True; "); var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { BuildWebHost(args).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(); } }
static void Main(string[] args) { var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (string.IsNullOrEmpty(environment)) { environment = "Development"; } var directory = Directory.GetCurrentDirectory(); var config = new ConfigurationBuilder() .SetBasePath(directory) .AddCommandLine(args) .AddJsonFile($"appsettings.{environment}.json") .Build(); var services = new ServiceCollection(); services.AddLogging(); var startup = new Startup(config); startup.ConfigureService(services); var containerBuilder = new Autofac.ContainerBuilder(); containerBuilder.Populate(services); var container = containerBuilder.Build(); var provider = new AutofacServiceProvider(container); var logger = provider.GetService <ILoggerFactory>(); logger.AddNLog(); GlobalDiagnosticsContext.Set("currentDirectory", directory); LogManager.LoadConfiguration("nlog.config"); IAction action = null; var jobConfig = config.GetSection("JobConfig").Get <JobConfig>(); switch (jobConfig.Action) { case "schedulePeriodicInspection": action = provider.GetService <SchedulePeriodicInspectionAction>(); break; } try { action?.Invoke().GetAwaiter().GetResult(); } catch (Exception ex) { var log = LogManager.GetCurrentClassLogger(); log.Error(ex); } }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { string sqlconnectstring = $"Data Source = cnclibdb.database.windows.net; Initial Catalog = CNCLibDb; Persist Security Info = True; User ID = {Xxx}; Password = {Yyy};"; // Open Database here if (env.IsDevelopment()) { sqlconnectstring = null; GlobalDiagnosticsContext.Set("connectionString", MigrationCNCLibContext.ConnectString); } else { GlobalDiagnosticsContext.Set("connectionString", sqlconnectstring); } Repository.SqlServer.MigrationCNCLibContext.InitializeDatabase(sqlconnectstring, false, false); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "CNCLib API V1"); }); app.UseCors("AllowAll"); app.UseMvc(); }
public static void Initialize(ScriptContext context) { var config = new NLog.Config.LoggingConfiguration(); // Targets where to log to: File and Console var logfile = new NLog.Targets.FileTarget("logfile") { FileName = GetDefaultLogPath(), Layout = "${date:format=HH\\:mm\\:ss:padding=-10:fixedlength=true} ${gdc:item=Script:padding=-20:fixedlength=true} ${level:uppercase=true:padding=-10:fixedlength=true} ${gdc:item=User:padding=-35:fixedlength=true} ${gdc:item=Patient:padding=-35:fixedlength=true} ${message}${onexception:${newline} ${exception:format=Message,StackTrace:separator=\r\n}}" }; // Rules for mapping loggers to targets config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile); // Apply config LogManager.Configuration = config; GlobalDiagnosticsContext.Set("Script", "Dosimetry Helper"); GlobalDiagnosticsContext.Set("User", $"{context.CurrentUser.Name} ({context.CurrentUser.Id})"); GlobalDiagnosticsContext.Set("Patient", $"{context.Patient.LastName}, {context.Patient.FirstName} ({context.Patient.Id})"); // Clear the log every day and save yesterday's log in case there were errors that need to be looked into if (File.Exists(GetDefaultLogPath()) && DateTime.Now.Day != File.GetLastWriteTime(GetDefaultLogPath()).Day) { File.Delete(GetOldLogPath()); File.Copy(GetDefaultLogPath(), GetOldLogPath()); File.Delete(GetDefaultLogPath()); } }
public static void Info(LoggingDestination destination, string input, [System.Runtime.CompilerServices.CallerMemberName] string caller = "") { Logger logger = LogManager.GetLogger(destination.ToString()); GlobalDiagnosticsContext.Set("custom", input); logger.Info("Info | {0} | {1}", caller, input); }
private void LoadGlobalDiagnosticsContextProperties(IDictionary <string, string> propertyBag) { foreach (string key in GlobalDiagnosticsContext.GetNames()) { this.PopulatePropertyBag(propertyBag, key, GlobalDiagnosticsContext.GetObject(key)); } }
public void OutputTest() { var config = new XmlLoggingConfiguration("NLog.Targets.ElasticSearch.Tests.dll.config"); LogManager.Configuration = config; var logger = LogManager.GetLogger("Example"); GlobalDiagnosticsContext.Set("test", null); logger.Trace("trace log message"); logger.Debug("debug log message: {0}", 1); logger.Info("info log message"); GlobalDiagnosticsContext.Set("test", "hi"); logger.Warn("warn log message"); logger.Error("error log message"); logger.Fatal("fatal log message"); var ev = new LogEventInfo(); ev.TimeStamp = DateTime.Now; ev.Level = LogLevel.Error; ev.Message = "log with property"; ev.Properties["hello"] = new TestData { Val1 = "hello" }; logger.Log(ev); Thread.Sleep(500); }