public static IServiceCollection AddDFrameHosting(this IServiceCollection services)
 {
     return(services.AddDFrameHosting(new ZLoggerOptions
     {
         ExceptionFormatter = (writer, ex) => ZString.Utf8Format(writer, "{0} {1}", ex.Message, ex.StackTrace),
     }));
 }
Example #2
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>()
            .UseUrls("http://*:8081");
        })
        .ConfigureLogging((context, builder) =>
        {
            builder.ClearProviders();

            if (context.HostingEnvironment.IsProduction())
            {
                //TODO..
            }

            builder.AddZLoggerConsole(options =>
            {
                options.PrefixFormatter = (writer, info) => ZString.Utf8Format(writer, "[{0}] [{1}] ", info.LogLevel.ToUpperString(), info.Timestamp.ToLocalTime().DateTime);
            });


            builder.AddZLoggerRollingFile((dt, x) => $"logs/{dt.ToLocalTime():yyyy-MM-dd}_{x:000}.log", x => x.ToLocalTime().Date, 1024 * 10,
                                          options =>
            {
                options.PrefixFormatter = (writer, info) => ZString.Utf8Format(writer, "[{0}] [{1}] ", info.LogLevel.ToUpperString(), info.Timestamp.ToLocalTime().DateTime);
            });
        })
        .ConfigureServices((context,
                            collection) => collection
                           .Configure <MongoSettings>((settings) =>
        {
            settings = context.Configuration.GetSection("MongoSettings").Get <MongoSettings>();
        }));
Example #3
0
        public void TextOptions()
        {
            var options = new ZLoggerOptions()
            {
                PrefixFormatter    = (writer, info) => ZString.Utf8Format(writer, "[Pre:{0}]", info.LogLevel),
                SuffixFormatter    = (writer, info) => ZString.Utf8Format(writer, "[Suf:{0}]", info.CategoryName),
                ExceptionFormatter = (writer, ex) => ZString.Utf8Format(writer, "{0}", ex.Message)
            };
            var processsor = new TestProcessor(options);

            var loggerFactory = LoggerFactory.Create(x =>
            {
                x.SetMinimumLevel(LogLevel.Debug);
                x.AddZLoggerLogProcessor(processsor);
            });
            var logger = loggerFactory.CreateLogger("test");

            logger.ZLogDebug("FooBar{0}-NanoNano{1}", 100, 200);
            processsor.Dequeue().Should().Be("[Pre:Debug]FooBar100-NanoNano200[Suf:test]");

            logger.ZLogInformation("FooBar{0}-NanoNano{1}", 100, 300);
            processsor.Dequeue().Should().Be("[Pre:Information]FooBar100-NanoNano300[Suf:test]");

            // fallback case
            logger.LogDebug("FooBar{0}-NanoNano{1}", 100, 200);
            processsor.Dequeue().Should().Be("[Pre:Debug]FooBar100-NanoNano200[Suf:test]");

            logger.LogInformation("FooBar{0}-NanoNano{1}", 100, 300);
            processsor.Dequeue().Should().Be("[Pre:Information]FooBar100-NanoNano300[Suf:test]");
        }
Example #4
0
        static async Task Main(string[] args)
        {
            Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", "Development");


            var host = Host.CreateDefaultBuilder()
                       .ConfigureServices(x =>
            {
            })
                       .ConfigureLogging(logging =>
            {
                logging.ClearProviders();

                logging.SetMinimumLevel(LogLevel.Trace);

                logging.AddZLoggerConsole(options =>
                {
                    options.EnableStructuredLogging = false;
                    //options.FlushRate = TimeSpan.FromSeconds(5);

#if DEBUG
                    // \u001b[31m => Red(ANSI Escape Code)
                    // \u001b[0m => Reset
                    // \u001b[38;5;***m => 256 Colors(08 is Gray)
                    options.PrefixFormatter = (writer, info) =>
                    {
                        if (info.LogLevel == LogLevel.Error)
                        {
                            ZString.Utf8Format(writer, "\u001b[31m[{0}]", info.LogLevel);
                        }
                        else
                        {
                            if (!info.CategoryName.StartsWith("MyApp"))     // your application namespace.
                            {
                                ZString.Utf8Format(writer, "\u001b[38;5;08m[{0}]", info.LogLevel);
                            }
                            else
                            {
                                ZString.Utf8Format(writer, "[{0}]", info.LogLevel);
                            }
                        }
                    };
                    options.SuffixFormatter = (writer, info) =>
                    {
                        if (info.LogLevel == LogLevel.Error || !info.CategoryName.StartsWith("MyApp"))
                        {
                            ZString.Utf8Format(writer, "\u001b[0m", "");
                        }
                    };
#endif
                }, configureEnableAnsiEscapeCode: true);
            })
                       .UseConsoleAppFramework <Program>(args)
                       .Build();

            GlobalLogger.SetServiceProvider(host.Services.GetRequiredService <ILoggerFactory>(), "MyApp");

            await host.RunAsync();
        }
Example #5
0
        internal static void Test <T0, T1>(bool testUtf8, string format, T0 t0, T1 t1)
        {
            {
                var actual   = ZString.Format(format, t0, t1);
                var expected = string.Format(format, t0, t1);
                actual.Should().Be(expected);
            }
            if (testUtf8)
            {
                var sb = ZString.CreateUtf8StringBuilder();
                sb.AppendFormat(format, t0, t1);
                var actual   = sb.ToString();
                var expected = string.Format(format, t0, t1);
                actual.Should().Be(expected);
            }

            // Prepare
            {
                var actual   = ZString.PrepareUtf16 <T0, T1>(format).Format(t0, t1);
                var expected = string.Format(format, t0, t1);
                actual.Should().Be(expected);
            }
            if (testUtf8)
            {
                var sb       = ZString.PrepareUtf8 <T0, T1>(format);
                var actual   = sb.Format(t0, t1);
                var expected = string.Format(format, t0, t1);
                actual.Should().Be(expected);
            }

            // Direct
            if (testUtf8)
            {
#if NETCOREAPP3_1
                var writer = new ArrayBufferWriter <byte>();
                ZString.Utf8Format(writer, format, t0, t1);
                var actual   = Encoding.UTF8.GetString(writer.WrittenSpan);
                var expected = string.Format(format, t0, t1);
                actual.Should().Be(expected);
#endif
            }
        }
Example #6
0
        public void AddManyProviderTest()
        {
            var factory = UnityLoggerFactory.Create(builder =>
            {
                builder.SetMinimumLevel(LogLevel.Debug);

                builder.AddZLoggerUnityDebug(x =>
                {
                    x.PrefixFormatter = (buf, info) => ZString.Utf8Format(buf, "UNI [{0}][{1}]", info.LogLevel, info.Timestamp.LocalDateTime);
                });
                builder.AddZLoggerFile("test_il2cpp.log", x =>
                {
                    x.PrefixFormatter = (buf, info) => ZString.Utf8Format(buf, "FIL [{0}][{1}]", info.LogLevel, info.Timestamp.LocalDateTime);
                });
            });

            var newLogger = factory.CreateLogger <NewTestScript>();

            newLogger.ZLogInformation("NEW OK INFO");
            newLogger.ZLogDebug("NEW OK DEBUG");
        }
Example #7
0
        public void AddFilterTest()
        {
            var factory = UnityLoggerFactory.Create(builder =>
            {
                builder.AddFilter <ZLoggerUnityLoggerProvider>("NewTestScript", LogLevel.Information);
                builder.AddFilter <ZLoggerUnityLoggerProvider>("OldTestScript", LogLevel.Debug);
                builder.AddZLoggerUnityDebug(x =>
                {
                    x.PrefixFormatter = (buf, info) => ZString.Utf8Format(buf, "[{0}][{1}]", info.LogLevel, info.Timestamp.LocalDateTime);
                });
            });

            var newLogger = factory.CreateLogger <NewTestScript>();
            var oldLogger = factory.CreateLogger("OldTestScript");

            newLogger.ZLogInformation("NEW OK INFO");
            newLogger.ZLogDebug("NEW OK DEBUG");

            oldLogger.ZLogInformation("OLD OK INFO");
            oldLogger.ZLogDebug("OLD OK DEBUG");
        }
Example #8
0
        void Test <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(string format, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16)
        {
            {
                var actual   = ZString.Format(format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16);
                var expected = string.Format(format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16);
                actual.Should().Be(expected);
            }
            {
                var sb = ZString.CreateUtf8StringBuilder();
                sb.AppendFormat(format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16);
                var actual   = sb.ToString();
                var expected = string.Format(format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16);
                actual.Should().Be(expected);
            }

            // Prepare
            {
                var actual   = ZString.PrepareUtf16 <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(format).Format(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16);
                var expected = string.Format(format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16);
                actual.Should().Be(expected);
            }
            {
                var sb       = ZString.PrepareUtf8 <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(format);
                var actual   = sb.Format(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16);
                var expected = string.Format(format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16);
                actual.Should().Be(expected);
            }

            // Direct
            {
#if NETCOREAPP3_1
                var writer = new ArrayBufferWriter <byte>();
                ZString.Utf8Format(writer, format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16);
                var actual   = Encoding.UTF8.GetString(writer.WrittenSpan);
                var expected = string.Format(format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16);
                actual.Should().Be(expected);
#endif
            }
        }
Example #9
0
        static async Task Main(string[] args)
        {
            Microsoft.Build.Locator.MSBuildLocator.RegisterDefaults();

            ApplicationLogging.SetLoggerFactory(LoggerFactory.Create(l => l.SetMinimumLevel(LogLevel.Information)
                                                                     .AddZLoggerConsole(options => options.PrefixFormatter = (buf, info) => ZString.Utf8Format(buf, "[{0}] [{1:D2}:{2:D2}:{3:D2}] ", GetLogLevelString(info.LogLevel), info.Timestamp.LocalDateTime.Hour, info.Timestamp.LocalDateTime.Minute, info.Timestamp.LocalDateTime.Second))));

            var settings = new H5DotJson_AssemblySettings();
            var request  = new CompilationRequest("App", settings)
                           .NoPackageResources()
                           .NoHTML()
                           .WithPackageReference("h5", NuGetVersion.Parse("0.0.8537"))
                           .WithPackageReference("h5.Core", NuGetVersion.Parse("0.0.8533"))
                           .WithSourceFile("App.cs",
                                           @"
using System;
using H5;

namespace Test
{
    internal static class App
    {
        private static int HelloWorld;
        private static void Main()
        {
            Console.WriteLine(nameof(HelloWorld));
        }
    }
}
");
            var compiledJavascript = await CompilationProcessor.CompileAsync(request);


            foreach (var(file, code) in compiledJavascript.Output)
            {
                Logger.ZLogInformation("File: {0}\n\n----------------------------\n\n{1}\n\n----------------------------\n\n", file, code);
            }

            await Task.Delay(1000); //Awaits to print all log messages
        }
Example #10
0
        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            //? If consoleOutputEncodingToUtf8 = true(default is true),
            //? set Console.OutputEncoding = new UTF8Encoding(false) when the provider is created.
            Console.OutputEncoding = new UTF8Encoding(true);

            //? optional(MS.E.Logging):clear default providers.
            logging.ClearProviders();

            //? optional(MS.E.Logging): default is Info,
            //? you can use this or AddFilter to filtering log.
            logging.SetMinimumLevel(LogLevel.Debug);

            //? Add Console Logging.
            logging.AddZLoggerConsole();

            //? Add File Logging.
            logging.AddZLoggerFile("fileName.log");

            //? Add Rolling File Logging.
            logging.AddZLoggerRollingFile((dt, x) =>
                                          $"logs/{dt.ToLocalTime():yyyy-MM-dd}_" +
                                          $"{x:000}.log", x => x.ToLocalTime().Date, 1024);

            //? Enable Structured Logging
            //? To setup, `EnableStructuredLogging = true`.
            //? ZLogger natively supports StructuredLogging and uses System.Text.Json.JsonSerializer
            logging.AddZLoggerConsole(options =>
            {
                options.EnableStructuredLogging = true;
            });


            //? Output to the Stream. This is useful when writing data to a MemoryStream or a NetworkStream.

            var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            //! socket.Connect("127.0.0.1", 12345);
            var network = new NetworkStream(socket);
            logging.AddZLoggerStream(network);


            //? ZLogger allows to add multiple same type providers. In this case, you need to give it a different name in string optionName.

            logging.AddZLoggerFile("plain-text.log", "file-plain", x =>
            {
                x.PrefixFormatter = (writer, info) =>
                                    ZString.Utf8Format(writer, "[{0}]", info.Timestamp.ToLocalTime().DateTime);
            });
            logging.AddZLoggerFile("json.log", "file-structured", x => { x.EnableStructuredLogging = true; });

            //? For performance reason, we do not use string so use the IBufferWriter<byte> instead.You can use ZString.Utf8Format to help set formatter.
            logging.AddZLoggerConsole(options =>
            {
                options.PrefixFormatter = (writer, info) =>
                                          ZString.Utf8Format(writer, "[{0}][{1}]", info.LogLevel, info.Timestamp.DateTime.ToLocalTime());

                // Tips: use PrepareUtf8 to achive better performance.
                var prefixFormat        = ZString.PrepareUtf8 <LogLevel, DateTime>("[{0}][{1}]");
                options.PrefixFormatter = (writer, info) =>
                                          prefixFormat.FormatTo(ref writer, info.LogLevel, info.Timestamp.DateTime.ToLocalTime());
            });

            //? output:
            //? [Information][04/07/2020 20:21:46]fooooo!
            //! logger.ZLogInformation("fooooo!");


            //? If you want to add additional information to the JSON, modify the StructuredLoggingFormatter as follows, for example

            logging.AddZLoggerConsole(options =>
            {
                options.EnableStructuredLogging = true;

                var gitHashName  = JsonEncodedText.Encode("GitHash");
                var gitHashValue = JsonEncodedText.Encode("gitHash");

                options.StructuredLoggingFormatter = (writer, info) =>
                {
                    writer.WriteString(gitHashName, gitHashValue);
                    info.WriteToJsonWriter(writer);
                };
            });

            //? {"GitHash":"XXXX","CategoryName":...,"Message":"...","Payload":...}
            //! logger.ZLog(....

            //? You can change the serialization behavior of the payload by changing the JsonSerializerOptions. If you want to set up a custom Converter, set it here. By default, the following configuration is used
            var js = new JsonSerializerOptions
            {
                WriteIndented    = false,
                IgnoreNullValues = false,
                Encoder          = JavaScriptEncoder.Create(UnicodeRanges.All)
            };

            //? Microsoft.CodeAnalysis.BannedApiAnalyzers
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup <Startup>();
        });