public static void Main(string[] args) { _configuration = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json") .AddCommandLine(args) .AddEnvironmentVariables() .AddUserSecrets(Assembly.GetExecutingAssembly()) .Build(); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(_configuration) .WriteTo.File(new JsonFormatter(), Path.Combine("logs", "log.json"), shared: true, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: 10_000_000, rollOnFileSizeLimit: true) .WriteTo.ColoredConsole() .CreateLogger(); try { Log.Information("Starting..."); CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { Log.Fatal(ex, "Failed start"); } finally { Log.CloseAndFlush(); } }
protected void WriteTabs(int n, WriteTo to = WriteTo.Header) { for (int i = 0; i < n; i++) { Write('\t', to); } }
protected void CloseFile(WriteTo to) { if (to == WriteTo.Buffer) return; _writers[to].Dispose(); _streams[to].Dispose(); }
protected void WriteTabs(int n, WriteTo to = WriteTo.WriterFlags) { for (int i = 0; i < n; i++) { Write('\t', to); } }
public static IWebHostBuilder UseSerilog( this IWebHostBuilder webHostBuilder, string appName, bool?serverCertificateValidationOverride = null) { webHostBuilder.UseSerilog((context, loggerConfiguration) => loggerConfiguration .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Error) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.ApplicationInsights( telemetryConfiguration: TelemetryConfiguration.Active, telemetryConverter: TelemetryConverter.Traces) .WriteTo.File( path: $"D:\\home\\LogFiles\\Application\\{appName}.txt", fileSizeLimitBytes: 1_000_000, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1), rollOnFileSizeLimit: true) .WriteTo.Elasticsearch( options: new ElasticsearchSinkOptions(context.Configuration.GetLogNodes()) { AutoRegisterTemplate = true, AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6, IndexFormat = $"{appName.ToLowerInvariant().Replace('.', '-')}-logs", CustomFormatter = new ExceptionAsObjectJsonFormatter(renderMessage: true), ModifyConnectionSettings = x => x.ServerCertificateValidationCallback( (o, certificate, arg3, arg4) => serverCertificateValidationOverride ?? arg4 == SslPolicyErrors.None) })); return(webHostBuilder); }
public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.FromLogContext() .Enrich.WithProperty("Application", "TodoApp.Api") .Enrich.WithProperty("Version", typeof(Program).Assembly.GetName().Version !.ToString()) .WriteTo.Console(new JsonFormatter()) .CreateLogger(); try { Log.Information("Starting up"); CreateHostBuilder(args).Build().Run(); } catch (Exception exc) { Log.Fatal(exc, "Error starting app: {ErrorMessage}", exc.Message); throw; } finally { Log.CloseAndFlush(); } }
public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() //possible to use appsettings .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System", LogEventLevel.Warning) .MinimumLevel.Override("Weather Service", LogEventLevel.Debug) .Enrich.FromLogContext() //.WriteTo.Console() .WriteTo.Console(new CompactJsonFormatter()) .WriteTo.File( $@"{AppDomain.CurrentDomain.BaseDirectory}/logs", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .WriteTo.Seq("http://localhost:5341") .CreateLogger(); try { Log.Information("Starting web host"); CreateHostBuilder(args).Build().Run(); } catch (Exception e) { Log.Fatal(e, "Host terminated unexpectedly"); } finally { Log.CloseAndFlush(); } }
private UniqueLogger CreateNewLogger(string uniqueId) { var loggingSwitch = new LoggingLevelSwitch(); var logger = new LoggerConfiguration() .WithIdentity(uniqueId) .MinimumLevel.Verbose() .WriteTo.Logger(subLogger => subLogger.MinimumLevel.ControlledBy(loggingSwitch) // .WriteTo.Console (outputTemplate:"[{Timestamp:HH:mm:ss} {Level:u3} {Identity}] {Message:lj}{NewLine}{Exception}") .WriteTo.File( $"logs/plugin_{uniqueId}_.log", outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Identity} {Level:u3}] {Message:lj}{NewLine}{Exception}", fileSizeLimitBytes: 100_000, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Hour, retainedFileCountLimit: 50, buffered: true, flushToDiskInterval: TimeSpan.FromSeconds(30) ) ) .WriteTo.Logger(_defaultLogger) .CreateLogger(); return(new UniqueLogger(uniqueId, logger, loggingSwitch)); }
public static int Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information) .MinimumLevel.Override("System", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information) .Enrich.FromLogContext() // uncomment to write to Azure diagnostics stream .WriteTo.File( @".\identityserver.txt", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Code) .CreateLogger(); try { Log.Information("Starting host..."); CreateHostBuilder(args).Build().Run(); return(0); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly."); return(1); } finally { Log.CloseAndFlush(); } }
private static void PrintOrgs(WriteTo write, ProgressCallback progress = null) { using (var db = new TransportContext()) { var p = 0; var max = db.Areas.Count(); // для каждой зоны записываем свой блок в файл foreach (var area in db.Areas.Include(a => a.Buildings .Select(b => b.OrgFils .Select(of => of.Org) .Select(o => o.OrgRubs)))) { const int lineLenght = 60; PrintLine('*', lineLenght, write); var buildingsCount = area.Buildings.Count; var orgFilsCount = area.Buildings.SelectMany(b => b.OrgFils).Count(); write($"{area.AreaId}. {area.Name} " + Environment.NewLine + $"Зданий: {buildingsCount} Жителей: {area.People} Организаций: {orgFilsCount}" + Environment.NewLine); PrintLine('-', lineLenght, write); var n = 1; foreach (var orgFil in area.Buildings.SelectMany(b => b.OrgFils)) { write($"{n++}. {orgFil.Org.Name}" + Environment.NewLine); } write(Environment.NewLine); progress?.Invoke(++p, max); } write(Environment.NewLine); } }
public static int Main(string[] args) { Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .Enrich.FromLogContext() .WriteTo.File( "applog.txt", outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .WriteTo.Console( outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}") .CreateLogger(); try { Log.Information("Getting the motors running..."); CreateHostBuilder(args).Build().Run(); return(0); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return(1); } finally { Log.CloseAndFlush(); } }
private static FeedData GetFeed(SyndicationFeed feed, string contentType, WriteTo writeTo) { var feedData = new FeedData { ContentType = contentType }; if (feed.Items.Any()) { SyndicationItem item = (from syndicationItem in feed.Items orderby syndicationItem.PublishDate descending select syndicationItem).First(); feedData.LastModifiedDate = item.PublishDate.DateTime; } else { feedData.LastModifiedDate = DateTime.MinValue; } var xmlWriterSettings = new XmlWriterSettings { Encoding = new UTF8Encoding(false) }; var memoryStream = new MemoryStream(); using (XmlWriter writer = XmlWriter.Create(memoryStream, xmlWriterSettings)) { writeTo(writer); } memoryStream.Position = 0; var sr = new StreamReader(memoryStream); feedData.Content = sr.ReadToEnd(); feedData.ETag = feedData.Content.GetHashCode().ToString(); //} return feedData; }
public static int Main(string[] args) { Console.Title = "IdentityServer Center"; const string outputTemplate = "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}"; Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information) .MinimumLevel.Override("System", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information) .Enrich.FromLogContext() // uncomment to write to Azure diagnostics stream .WriteTo.File( @"LogFiles\log.log", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, restrictedToMinimumLevel: LogEventLevel.Warning, rollingInterval: RollingInterval.Day, outputTemplate: outputTemplate, flushToDiskInterval: TimeSpan.FromSeconds(1)) .WriteTo.Console(outputTemplate: outputTemplate, theme: AnsiConsoleTheme.Code) .CreateLogger(); try { var seed = args.Contains("/seed"); if (seed) { args = args.Except(new[] { "/seed" }).ToArray(); } var host = CreateHostBuilder(args).Build(); if (seed) { Log.Information("Seeding database..."); SeedData.EnsureSeedData(host.Services); Log.Information("Done seeding database."); } Log.Information("Starting host..."); host.Run(); return(0); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly."); return(1); } finally { Log.Information("Host Closed."); Log.CloseAndFlush(); } }
private static void PrintLine(char symbol, int count, WriteTo write) { for (var i = 0; i < count; i++) { write(symbol.ToString()); } write(Environment.NewLine); }
public static int Main(string[] args) { AppVersionInfo.InitialiseBuildInfoGivenPath(AppDomain.CurrentDomain.BaseDirectory); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information) .MinimumLevel.Override("System", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information) .Enrich.FromLogContext() // uncomment to write to Azure diagnostics stream .WriteTo.File( @"D:\home\LogFiles\Application\identityserver.txt", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", theme: AnsiConsoleTheme.Code) .CreateLogger(); try { var seed = args.Contains("/seed"); if (seed) { args = args.Except(new[] { "/seed" }).ToArray(); } var host = CreateHostBuilder(args) .Build(); if (seed) { Log.Information("Seeding database..."); var config = host.Services.GetRequiredService <IConfiguration>(); var connectionString = config["SqlConnection"]; SeedData.EnsureSeedData(connectionString); Log.Information("Done seeding database."); return(0); } Log.Information("Starting host..."); host.Run(); return(0); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly."); return(1); } finally { Log.CloseAndFlush(); } }
protected void CloseFile(WriteTo to) { if (to == WriteTo.Buffer) { return; } _writers[to].Dispose(); _streams[to].Dispose(); }
public XUnitAutoTestLoggerConfiguration(ITestOutputHelper output, LogEventLevel level = LogEventLevel.Verbose, string logFileName = null) : base(level, logFileName) { //dont want overload CI console output with logs if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("CI"))) { level = LogEventLevel.Warning; } WriteTo.XunitTestOutput(output, level, DefaultTemplate); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddInfrastructure(); services.AddControllers(); Log.Logger = new LoggerConfiguration() .WriteTo.File("log.txt", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true) .WriteTo.Console() .WriteTo.Seq("http://localhost:5341") .CreateLogger(); services.AddSingleton <Serilog.ILogger>(Log.Logger); }
public static void ConfigureLogging(this IServiceCollection _) { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .MinimumLevel.Information() // .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) // .MinimumLevel.Override("System", LogEventLevel.Warning) .WriteTo.Console() # if DEBUG .WriteTo.Seq("http://localhost:5341") # endif .CreateLogger(); }
protected void WriteLine(WriteTo to = WriteTo.WriterFlags) { if (to == WriteTo.WriterFlags) { to = To; } Write("\r\n", to); foreach (var toFlag in GetIndividualFlags(to)) { LineLengths[toFlag] = 0; } }
private static void InitLogger() { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .Destructure.ByTransforming <JsonWebToken>(jwt => { var result = new Dictionary <string, object>(); foreach (var claim in jwt.Claims) { if (result.TryGetValue(claim.Type, out var value)) { var list = value as List <string>; if (list == null) { list = new List <string>(); list.Add((string)value); result[claim.Type] = list; } list.Add(claim.Value); } else { var claimValue = claim.Value; switch (claim.Type) { case "exp": case "nbf": case "iat": if (long.TryParse(claimValue, out var timestamp)) { var dt = DateTimeOffset.FromUnixTimeSeconds(timestamp).ToLocalTime(); claimValue += $" (which is {dt})"; } break; } result.Add(claim.Type, claimValue); } } return(result); }) .WriteTo.Console() .CreateLogger(); }
protected void OpenFile(string filename, WriteTo to) { if (to == WriteTo.Buffer) { _bufferBuilder = new StringBuilder(); } else { _streams[to] = new FileStream(filename, FileMode.Create, FileAccess.Write); _writers[to] = new StreamWriter(_streams[to]); } LineLengths[to] = 0; To = to; }
public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() .Enrich.FromLogContext() .MinimumLevel.Override("Microsoft", LogEventLevel.Error) // new CompactJsonFormatter(), .WriteTo.File(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @$ "Logs", @$ "{DateTime.Now.Date.ToString(" yyyyMMdd ")}", @"log.txt"), rollingInterval: RollingInterval.Minute) .WriteTo.Elasticsearch(new Serilog.Sinks.Elasticsearch.ElasticsearchSinkOptions(new Uri("http://localhost:9200/")) { AutoRegisterTemplate = true, }) .CreateLogger(); CreateHostBuilder(args).Build().Run(); }
public static IWriteTo GetObject(WriteTo writeTo) { IWriteTo ObjSelector = null; switch (writeTo) { case WriteTo.WriteToDataBase: { ObjSelector = new WriteToDatabse(); } break; case WriteTo.WriteToFile: { ObjSelector = new WriteToFile(); } break; } return ObjSelector; }
public static void Main(string[] args) { var db = documentClient.GetDatabase("log"); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .Enrich.WithProperty("App Name", "API Core") .Enrich.FromLogContext() .WriteTo.Logger(lc => lc.Filter.ByExcluding(Matching.WithProperty("AuditLog")) .WriteTo.Console(new ElasticsearchJsonFormatter()) .Enrich.WithThreadName() //.WriteTo.MongoDB(db,collectionName:"apiFull") .WriteTo.Debug() .WriteTo.File(@"d:\log\serilog\logCore.txt", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) ) .WriteTo.Logger(lc => lc.Filter.ByIncludingOnly(Matching.WithProperty("AuditLog")) .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://localhost:9200")) { AutoRegisterTemplate = true, AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv6, //PipelineName = "ApiCoreTestPipeline", //TypeName = "ApiCoreTesType" }) .WriteTo.MongoDB(db, collectionName: "logCore") ) .CreateLogger(); try { Log.Information("Starting API Core Serilog"); CreateHostBuilder(args).Build().Run(); return; } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return; } finally { Log.CloseAndFlush(); } }
public static IWriteTo GetObject(WriteTo writeTo) { IWriteTo ObjSelector = null; switch (writeTo) { case WriteTo.WriteToDataBase: { ObjSelector = new WriteToDatabse(); } break; case WriteTo.WriteToFile: { ObjSelector = new WriteToFile(); } break; } return(ObjSelector); }
public ReplicatorSpec(ReplicatorSpecConfig config) : base(config) { _config = config; _cluster = Cluster.Cluster.Get(Sys); var settings = ReplicatorSettings.Create(Sys).WithGossipInterval(TimeSpan.FromSeconds(1.0)).WithMaxDeltaElements(10); var props = Replicator.Props(settings); _replicator = Sys.ActorOf(props, "replicator"); _timeOut = Dilated(TimeSpan.FromSeconds(2.0)); _writeTwo = new WriteTo(2, _timeOut); _writeMajority = new WriteMajority(_timeOut); _writeAll = new WriteAll(_timeOut); _readTwo = new ReadFrom(2, _timeOut); _readMajority = new ReadMajority(_timeOut); _readAll = new ReadAll(_timeOut); }
public static async Task Main(string[] args) { var path = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LOG"), "ELA_AUTH_LOG.txt"); //ELA_AUTH_LOG.txt Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.File( path, fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .WriteTo.Console() .CreateLogger(); try { var host = CreateHostBuilder(args).Build(); using (var serviceScope = host.Services.CreateScope()) { var dbContext = serviceScope.ServiceProvider.GetRequiredService <ElaAuthContext>(); await dbContext.Database.MigrateAsync(); var roleManager = serviceScope.ServiceProvider.GetRequiredService <RoleManager <IdentityRole> >(); var userManager = serviceScope.ServiceProvider.GetRequiredService <UserManager <AppUser> >(); var mySql = serviceScope.ServiceProvider.GetRequiredService <MySqlDataContext>(); var baseIdentityInitializer = new InitializeIdentity(dbContext, userManager, roleManager, mySql); await baseIdentityInitializer.Initialize(); } await host.RunAsync(); } catch (Exception e) { Log.Fatal(e, "Application start-up failed"); } finally { Log.CloseAndFlush(); } }
public static int Main(string[] args) { Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() // Add this line: .WriteTo.File( @"log\myappMain.log", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, rollingInterval: RollingInterval.Day, outputTemplate: outputTemplate, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .WriteTo.File( @"log\myappMain.error.log", LogEventLevel.Error, fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, outputTemplate: outputTemplate, rollingInterval: RollingInterval.Day, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .CreateLogger(); try { Log.Information("Starting web host"); Log.Error("Starting web host test error"); CreateHostBuilder(args).Build().Run(); return(0); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return(1); } finally { Log.CloseAndFlush(); } }
protected void Write(string s, WriteTo to = WriteTo.AllFiles) { if ((to & WriteTo.Header) != 0) { headerWriter.Write(s); } if ((to & WriteTo.Source) != 0) { sourceWriter.Write(s); } if ((to & WriteTo.CS) != 0) { csWriter.Write(s); } if ((to & WriteTo.Buffer) != 0) { bufferBuilder.Append(s); } }
protected void EnsureWhiteSpace(WriteTo to) { if ((to & WriteTo.Source) != 0) { if (!hasSourceWhiteSpace) { sourceWriter.WriteLine(); hasSourceWhiteSpace = true; } } if ((to & WriteTo.CS) != 0) { if (!hasCSWhiteSpace) { csWriter.WriteLine(); hasCSWhiteSpace = true; } } }
public static async Task <IHostBuilder> RunWithSerilogAsync(this IHostBuilder hostBuilder) { Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Debug() .WriteTo.Console(new RenderedCompactJsonFormatter() 0) //.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}") .WriteTo.File(new RenderedCompactJsonFormatter(), "/logs/log.ndjson") .WriteTo.Seq(Environment.GetEnvironmentVariable("SEQ_URL") ?? "http://localhost:5341") .CreateLogger() ; try { Log.Information("Starting up"); hostBuilder.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration .ReadFrom.Configuration(hostingContext.Configuration) .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Debug() .WriteTo.Console(new RenderedCompactJsonFormatter() 0) //.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}") .WriteTo.File(new RenderedCompactJsonFormatter(), "/logs/log.ndjson") .WriteTo.Seq(Environment.GetEnvironmentVariable("SEQ_URL") ?? "http://localhost:5341") ); await hostBuilder.Build().RunAsync(); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); Log.Fatal(ex, "Application start-up failed"); } finally { Log.CloseAndFlush(); } return(hostBuilder); }
public static void Main(string[] args) { var config = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore.SpaServices", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext} {Message:lj}{NewLine}{Exception}") .WriteTo.Trace(); var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); var isDevelopment = environment == Environments.Development; if (!isDevelopment) { config = config .WriteTo.File( @"D:\home\LogFiles\Application\myapp.txt", fileSizeLimitBytes: 1_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .WriteTo.ApplicationInsights(TelemetryConverter.Traces); } Log.Logger = config.CreateLogger(); try { Log.Information("Starting web host"); CreateWebHostBuilder(args).Build().Run(); } catch (Exception e) { Log.Fatal(e, "Host terminated unexpectedly"); } finally { Log.CloseAndFlush(); } }
private static IEnumerable<WriteTo> GetIndividualFlags(WriteTo to) { if ((to & WriteTo.Header) != 0) { yield return WriteTo.Header; } if ((to & WriteTo.Source) != 0) { yield return WriteTo.Source; } if ((to & WriteTo.CS) != 0) { yield return WriteTo.CS; } if ((to & WriteTo.Buffer) != 0) { yield return WriteTo.Buffer; } if ((to & WriteTo.CMake) != 0) { yield return WriteTo.CMake; } }
protected void WriteLine(WriteTo to = WriteTo.WriterFlags) { if (to == WriteTo.WriterFlags) to = To; Write("\r\n", to); foreach (var toFlag in GetIndividualFlags(to)) { LineLengths[toFlag] = 0; } }
void WriteType(TypeRefDefinition type, WriteTo writeTo) { string typeName = BulletParser.GetTypeName(type) ?? string.Empty; Write(typeName.Replace("::", "_"), writeTo & (WriteTo.Source | WriteTo.Header)); }
void WriteType(TypeRefDefinition type, WriteTo writeTo) { if (type.IsBasic) { Write(type.Name.Replace("::", "_"), writeTo & WriteTo.Header); Write(type.Name, writeTo & WriteTo.Source); } else if (type.HasTemplateTypeParameter) { } else { string typeName; if (type.Referenced != null) { if (type.Referenced.IsConst) // || type.IsConst { Write("const ", writeTo); } typeName = BulletParser.GetTypeName(type.Referenced) ?? string.Empty; } else { if (type.IsConst) { Write("const ", writeTo); } typeName = BulletParser.GetTypeName(type); } if (type.Target != null && type.Target.IsPureEnum) { Write(typeName + "::" + type.Target.Enum.Name, writeTo & WriteTo.Source); Write(typeName.Replace("::", "_"), writeTo & WriteTo.Header); } else { Write(typeName + '*', writeTo & WriteTo.Source); Write(typeName.Replace("::", "_") + '*', writeTo & WriteTo.Header); } } }
protected void Write(string s, WriteTo to = WriteTo.WriterFlags) { if (to == WriteTo.WriterFlags) to = To; int sLength = s.Length + s.Count(c => c == '\t') * (TabWidth - 1); foreach (var toFlag in GetIndividualFlags(to)) { if (toFlag == WriteTo.Buffer) { _bufferBuilder.Append(s); } else { _writers[toFlag].Write(s); } LineLengths[toFlag] += sLength; } }
public static void WriteLine(string line, WriteTo to, IEnumerable<Stream> streams) { if (to == WriteTo.None) return; Contract.Requires(line != null, "line != null"); if ((to & WriteTo.Debug) != 0) Debug.WriteLine(line); if ((to & WriteTo.Trace) != 0) Trace.TraceInformation(line); if ((to & WriteTo.Console) != 0) Console.WriteLine(line); if (streams != null) { var uniqueStreams = new HashSet<Stream>(streams.Where(s => s != null)); if (uniqueStreams.Count > 0 && (to & WriteTo.Streams) != 0) { var bytes = System.Text.Encoding.Unicode.GetBytes(line + "\r\n"); foreach (var s in uniqueStreams) if (s.CanWrite) s.Write(bytes, 0, bytes.Count()); } } }
protected void WriteLine(string s, WriteTo to = WriteTo.WriterFlags) { Write(s, to); WriteLine(to); }
protected void Write(char c, WriteTo to = WriteTo.WriterFlags) { Write(c.ToString(), to); }
protected void WriteLine(char c, WriteTo to = WriteTo.WriterFlags) { Write(c, to); WriteLine(to); }
protected void WriteLine(WriteTo to = WriteTo.AllFiles) { Write("\r\n", to); }
protected void WriteLine(char c, WriteTo to = WriteTo.AllFiles) { Write(c, to); WriteLine(to); }
protected void WriteLine(string s, WriteTo to = WriteTo.AllFiles) { Write(s, to); WriteLine(to); }
protected void Write(char c, WriteTo to = WriteTo.AllFiles) { Write(c.ToString(), to); }
protected void EnsureWhiteSpace(WriteTo to = WriteTo.WriterFlags) { if (to == WriteTo.WriterFlags) to = To; if ((to & WriteTo.Source) != 0) { if (!hasSourceWhiteSpace) { WriteLine(WriteTo.Source); hasSourceWhiteSpace = true; } } if ((to & WriteTo.CS) != 0) { if (!hasCSWhiteSpace) { WriteLine(WriteTo.CS); hasCSWhiteSpace = true; } } }
/// <summary> /// Takes a collection of strings, joins them by commas /// and breaks lines if necessary. /// </summary> /// <param name="list">Collection of strings.</param> /// <param name="to">Where the list will be written to.</param> /// <param name="level">How many tabs to insert to the start of a line.</param> /// <returns></returns> protected string ListToLines(IEnumerable<string> list, WriteTo to, int level = 0) { int lineLength = LineLengths[to]; return list.Aggregate("", (a, p) => { if (lineLength > LineBreakWidth) { string tabs = new string('\t', level + 1); lineLength = tabs.Length * 4 + p.Length; if (a.Length == 0) return $"\r\n{tabs}{p}"; return $"{a},\r\n{tabs}{p}"; } lineLength += 2 + p.Length; if (a.Length == 0) return p; return $"{a}, {p}"; }); }
public virtual void Initialise(XElement xElement, IDocumentAccessor accessor) { xElement = Persistence.ThisOrSingleChild(XName, xElement); IEnumerable<IArgument> arguments; IEnumerable<IBaseInput> inputs; IEnumerable<IBaseOutput> outputs; Identity = Persistence.BaseComponent.Parse(xElement, accessor, out arguments, out inputs, out outputs); Arguments = arguments.ToList(); SetArgCaption(); Inputs = inputs.ToList(); Outputs = outputs.ToList(); foreach (var i in Inputs) if (i is BaseExchangeItem) ((BaseExchangeItem)i).Component = this; foreach (var i in Outputs) if (i is BaseExchangeItem) ((BaseExchangeItem)i).Component = this; _useNativeDll = Utilities.Xml.GetAttribute(xElement, "useNativeDllArgument", false); int traceTo = int.Parse(Utilities.Xml.GetAttribute(xElement, "traceTo")); _writeTo = (WriteTo)traceTo; var derivedComponentType = xElement .Elements("DerivedComponentType") .SingleOrDefault(); _derivedComponentType = derivedComponentType != null ? new ExternalType(derivedComponentType, accessor) : null; var engineType = xElement .Elements("EngineType") .SingleOrDefault(); _engineType = engineType != null ? new ExternalType(engineType, accessor) : null; _engine = null; _activeInputs = new List<IBaseInput>(); _activeOutputs = new List<IBaseOutput>(); }
protected void WriteLine(int numTabs, string s, WriteTo to = WriteTo.WriterFlags) { WriteTabs(numTabs, to); WriteLine(s, to); }