public static void LoadLogging(Action <LogEvent, string, string> handler) { // Serilog.Formatting.Display.MessageTemplateTextFormatter tf = new Serilog.Formatting.Display.MessageTemplateTextFormatter(outputTemplate, CultureInfo.InvariantCulture); // Install-Package Serilog.Enrichers.Demystify -Pre -DependencyVersion Highest ITextFormatter jsonFormatter = new JsonFormatter(renderMessage: true); var outputTemplate = "[{Timestamp:mm:ss}]-[{Level:u3}] {Message:lj} {Exception}"; var tf = new Serilog.Formatting.Display.MessageTemplateTextFormatter(outputTemplate, CultureInfo.InvariantCulture); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .Enrich.FromLogContext() // Enables class/function name in logs .Enrich.WithExceptionDetails() // Enables full exception information .Enrich.WithDemystifiedStackTraces() // Enables a more readable stack trace (Serilog.Enrichers.Demystify) // .Enrich.WithCaller() .WriteTo.Trace() // Enables VS console logging .WriteTo.ObservableCollection(handler, tf, jsonFormatter) .WriteTo.RollingFile(jsonFormatter, string.Empty) .CreateLogger(); // Logger.CreateLogger(configRoot, directories.AppLogDir, ShowLogMessage); Log.Information("Started"); }
public void Emit(LogEvent logEvent) { ITextFormatter x = new Serilog.Formatting.Display.MessageTemplateTextFormatter(OutputTemplate); var stringWrite = new StringWriter(); x.Format(logEvent, stringWrite); LastLogEntry = $"{logEvent.Level}:{stringWrite}".Trim(); }
static void Main(string[] args) { if (args.Length < 3) { throw new ArgumentException("Must provide a config file, aws profile and path"); } var config = args[0]; var isConsole = args.Length == 4 && args[3].Equals("--console"); var outputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}"; if (args.Length == 4 && !args[3].Equals("--console")) { // Args[3] is version number if not --console outputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] (" + args[3] + ") {SourceContext}: {Message:lj}{NewLine}{Exception}"; } Serilog.Formatting.Display.MessageTemplateTextFormatter tf = new Serilog.Formatting.Display.MessageTemplateTextFormatter(outputTemplate, CultureInfo.InvariantCulture); var portingAssistantSink = new PortingAssistantSink(tf); var logConfiguration = new LoggerConfiguration().Enrich.FromLogContext() .MinimumLevel.Debug() .WriteTo.RollingFile( Path.Combine(args[2], "logs", "portingAssistant-assessment-{Date}.log"), outputTemplate: outputTemplate) .WriteTo.Sink(portingAssistantSink); if (isConsole) { logConfiguration = logConfiguration.WriteTo.Console(); } Log.Logger = logConfiguration.CreateLogger(); var portingAssistantPortingConfiguration = JsonSerializer.Deserialize <PortingAssistantPortingConfiguration>(File.ReadAllText(config)); var configuration = new PortingAssistantConfiguration(); configuration.DataStoreSettings.HttpsEndpoint = portingAssistantPortingConfiguration.PortingAssistantConfiguration.DataStoreSettings.HttpsEndpoint; configuration.DataStoreSettings.S3Endpoint = portingAssistantPortingConfiguration.PortingAssistantConfiguration.DataStoreSettings.S3Endpoint; configuration.DataStoreSettings.GitHubEndpoint = portingAssistantPortingConfiguration.PortingAssistantConfiguration.DataStoreSettings.GitHubEndpoint; var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection, configuration); try { var application = new Application(serviceCollection, portingAssistantSink); application.SetupConnection(isConsole); application.Start(); } finally { Log.CloseAndFlush(); } }
public static LoggerConfiguration NUnit( this LoggerSinkConfiguration loggerConfiguration, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, IFormatProvider formatProvider = null, LoggingLevelSwitch levelSwitch = null) { string outputTemplate = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"; var formatter = new Serilog.Formatting.Display.MessageTemplateTextFormatter(outputTemplate, formatProvider); return(loggerConfiguration.Sink(new NUnitSink(formatter), restrictedToMinimumLevel, levelSwitch)); }
public void SuccessfulLogger() { var config = new RedisStreamSinkConfiguration { RedisConnectionString = "a", RedisStreamName = "b", RedisStreamMessageField = "c" }; string outputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}"; IFormatProvider formatProvider = null; var formatter = new Serilog.Formatting.Display.MessageTemplateTextFormatter(outputTemplate, formatProvider); var template = new MessageTemplateParser().Parse("{TestToken} is good"); var properties = new List <LogEventProperty> { new LogEventProperty("TestToken", new ScalarValue("Ice Cream")) }; var mockDatabase = BuildDatabase("SUCCESS_ID"); var mockMultiplexer = BuildSuccessConnectionMultiplexer(mockDatabase); var mockSink = new Mock <RedisStreamSink>(config, formatter) { CallBase = true }; mockSink.Setup(_ => _.ConnectToRedis()) .Returns(mockMultiplexer.Object); var loggingEvent = new LogEvent(DateTimeOffset.Now, LogEventLevel.Information, null, template, properties); mockSink.Object.Emit(loggingEvent); Assert.True(true); }
static void Main(string[] args) { PortingAssistantCLI cli = new PortingAssistantCLI(); cli.HandleCommand(args); var logConfiguration = new LoggerConfiguration().Enrich.FromLogContext() .MinimumLevel.Debug() .WriteTo.Console(); var assemblypath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var telemetryConfiguration = JsonSerializer.Deserialize <TelemetryConfiguration>(File.ReadAllText(Path.Combine(assemblypath, "PortingAssistantTelemetryConfig.json"))); var configuration = new PortingAssistantConfiguration(); var roamingFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); var logs = Path.Combine(roamingFolder, "Porting Assistant for .NET", "logs"); var logFilePath = Path.Combine(logs, "portingAssistant-client-cli.log"); var metricsFilePath = Path.Combine(logs, "portingAssistant-client-cli.metrics"); string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion; var outputTemplate = "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] (Porting Assistant Client CLI) (" + version + ") (" + cli.Tag + ") {SourceContext}: {Message:lj}{NewLine}{Exception}"; Serilog.Formatting.Display.MessageTemplateTextFormatter tf = new Serilog.Formatting.Display.MessageTemplateTextFormatter(outputTemplate, CultureInfo.InvariantCulture); logConfiguration.WriteTo.File( logFilePath, rollingInterval: RollingInterval.Infinite, rollOnFileSizeLimit: false, outputTemplate: outputTemplate); Log.Logger = logConfiguration.CreateLogger(); if (cli.isSchema) { if (cli.schemaVersion) { Console.WriteLine(Common.Model.Schema.version); } } if (cli.isAssess) { try { TelemetryCollector.Builder(Log.Logger, metricsFilePath); var portingAssistantBuilder = PortingAssistantBuilder.Build(configuration, logConfig => logConfig.SetMinimumLevel(LogLevel.Debug) .AddSerilog(logger: Log.Logger, dispose: true)); var portingAssistantClient = portingAssistantBuilder.GetPortingAssistant(); var reportExporter = portingAssistantBuilder.GetReportExporter(); var solutionSettings = cli.IgnoreProjects != null && cli.IgnoreProjects.Count != 0 ? new AnalyzerSettings { IgnoreProjects = cli.IgnoreProjects, TargetFramework = cli.Target } : new AnalyzerSettings { IgnoreProjects = new List <string>(), TargetFramework = cli.Target }; var startTime = DateTime.Now; Task <SolutionAnalysisResult> analyzeResults; if (solutionSettings.UseGenerator) { analyzeResults = AnalyzeSolutionGenerator(portingAssistantClient, cli.SolutionPath, solutionSettings); } else { analyzeResults = portingAssistantClient.AnalyzeSolutionAsync(cli.SolutionPath, solutionSettings); analyzeResults.Wait(); } if (analyzeResults.IsCompletedSuccessfully) { reportExporter.GenerateJsonReport(analyzeResults.Result, cli.OutputPath); TelemetryCollector.SolutionAssessmentCollect(analyzeResults.Result, cli.Target, "1.8.0", $"Porting Assistant Client CLI", DateTime.Now.Subtract(startTime).TotalMilliseconds, cli.Tag); } else { Log.Logger.Error("err generated solution analysis report"); } if (cli.PortingProjects != null && cli.PortingProjects.Count != 0) { var PortingProjectResults = analyzeResults.Result.ProjectAnalysisResults .Where(project => cli.PortingProjects.Contains(project.ProjectName)); var FilteredRecommendedActions = PortingProjectResults .SelectMany(project => project.PackageAnalysisResults.Values .Where(package => { var comp = package.Result.CompatibilityResults.GetValueOrDefault(cli.Target); return(comp.Compatibility != Compatibility.COMPATIBLE && comp.CompatibleVersions.Count != 0); }) .SelectMany(package => package.Result.Recommendations.RecommendedActions)); var PortingRequest = new PortingRequest { Projects = analyzeResults.Result.SolutionDetails.Projects.Where(p => cli.PortingProjects.Contains(p.ProjectName)).ToList(), SolutionPath = cli.SolutionPath, TargetFramework = cli.Target.ToString(), RecommendedActions = FilteredRecommendedActions.ToList(), IncludeCodeFix = true }; var portingResults = portingAssistantClient.ApplyPortingChanges(PortingRequest); reportExporter.GenerateJsonReport(portingResults, cli.SolutionPath, cli.OutputPath); } UploadLogs(cli.Profile, telemetryConfiguration, logFilePath, metricsFilePath, logs); } catch (Exception ex) { Log.Logger.Error(ex, "error when using the tools :"); UploadLogs(cli.Profile, telemetryConfiguration, logFilePath, metricsFilePath, logs); Environment.Exit(-1); } } }
private static LoggerConfiguration configFromWebApiConfig(LoggerConfiguration loggerConfiguration, WebApiConfig apiConfig) { apiConfig = apiConfig ?? new WebApiConfig(); loggerConfiguration.MinimumLevel.ControlledBy(apiConfig.InnerSerilogLevels.AppLogLevel) .MinimumLevel.Override("Microsoft", apiConfig.InnerSerilogLevels.SystemLogLevel) .MinimumLevel.Override("System", apiConfig.InnerSerilogLevels.SystemLogLevel) .MinimumLevel.Override("Microsoft.AspNetCore", apiConfig.InnerSerilogLevels.AppLogLevel) .MinimumLevel.Override("Microsoft.Hosting", apiConfig.InnerSerilogLevels.AppLogLevel) .MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", apiConfig.InnerSerilogLevels.EFCoreCommandLevel) .MinimumLevel.Override("System.Net.Http.HttpClient", apiConfig.InnerSerilogLevels.AppLogLevel) .MinimumLevel.Override("ServerRequest.Logger", apiConfig.InnerSerilogLevels.ServerRequestLevel) .MinimumLevel.Override("ClientRequest.Logger", apiConfig.InnerSerilogLevels.ClientRequestLevel) .Destructure.ToMaximumStringLength(apiConfig.MaxLogLength); loggerConfiguration = loggerConfiguration.Enrich.FromLogContext(); if (apiConfig.ConsoleJsonLog) { loggerConfiguration = loggerConfiguration.WriteTo.Console(new CompactJsonFormatter(apiConfig)); } else if (apiConfig.ConsoleLog) { loggerConfiguration = loggerConfiguration.WriteTo.Console(); } else { loggerConfiguration = loggerConfiguration.WriteTo.Console(Serilog.Events.LogEventLevel.Warning); } if (apiConfig.FileLog || apiConfig.FileJsonLog) { string path = apiConfig.GetLogPath(); string pathTemplate = apiConfig.LogPathTemplate; if (string.IsNullOrEmpty(pathTemplate)) { pathTemplate = LogPathTemplates.DayFolderAndLoggerNameFile; } Serilog.Formatting.Display.MessageTemplateTextFormatter pathFormatter = new Serilog.Formatting.Display.MessageTemplateTextFormatter(pathTemplate); ArchiveHooks archiveHooks = new ArchiveHooks(CompressionLevel.Fastest); string template = apiConfig.LogTemplate; if (string.IsNullOrEmpty(template)) { template = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{NewLine}{Exception}"; } bool keySelector(Serilog.Events.LogEvent logEvent, out LogPathAndTimeKey key) { StringWriter sw = new StringWriter(); StringBuilder sb = new StringBuilder(); pathFormatter.Format(logEvent, sw); sw.Flush(); string dp = sw.GetStringBuilder().ToString(); string p = Path.Combine(path, dp); key = new LogPathAndTimeKey() { Path = p, Time = logEvent.Timestamp.Date }; return(true); }; if (apiConfig.FileJsonLog) { var formatter = new CompactJsonFormatter(apiConfig); loggerConfiguration = loggerConfiguration .WriteTo.MapCondition <LogPathAndTimeKey>(keySelector, (path, lc) => { lc.Async(lc => lc.File( formatter, path.Path, rollingInterval: RollingInterval.Infinite, rollOnFileSizeLimit: true, fileSizeLimitBytes: apiConfig.MaxLogFileSize, retainedFileCountLimit: apiConfig.RetainedFileCount, hooks: archiveHooks)); }, key => { // 自动Dispose前一天的日志 DateTimeOffset now = DateTimeOffset.Now.Date; if (now > key.Time.Date) { return(true); } return(false); }); } else { loggerConfiguration = loggerConfiguration .WriteTo.MapCondition <LogPathAndTimeKey>(keySelector, (path, lc) => { lc.Async(lc => lc.File( path.Path, rollingInterval: RollingInterval.Infinite, rollOnFileSizeLimit: true, fileSizeLimitBytes: apiConfig.MaxLogFileSize, retainedFileCountLimit: apiConfig.RetainedFileCount, hooks: archiveHooks, outputTemplate: template)); }, key => { // 自动Dispose前一天的日志 DateTimeOffset now = DateTimeOffset.Now.Date; if (now > key.Time.Date) { return(true); } return(false); }); } } return(loggerConfiguration); }