public static Action <ILogger, T1, T2, T3, T4, Exception> Define <T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string format)
        {
            var prepared = ZString.PrepareUtf8 <T1, T2, T3, T4>(format);

            return((ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception ex) =>
            {
                logger.Log(logLevel, eventId, new PreparedFormatLogState <object, T1, T2, T3, T4>(null, prepared, arg1, arg2, arg3, arg4), ex, (state, _) =>
                {
                    return state.Format.Format(state.Arg1, state.Arg2, state.Arg3, state.Arg4);
                });
            });
        }
        public static Action <ILogger, TPayload, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, Exception> DefineWithPayload <TPayload, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(LogLevel logLevel, EventId eventId, string format)
        {
            var prepared = ZString.PrepareUtf8 <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(format);

            return((ILogger logger, TPayload payload, 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, Exception ex) =>
            {
                logger.Log(logLevel, eventId, new PreparedFormatLogState <TPayload, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(payload, prepared, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13), ex, (state, _) =>
                {
                    return state.Format.Format(state.Arg1, state.Arg2, state.Arg3, state.Arg4, state.Arg5, state.Arg6, state.Arg7, state.Arg8, state.Arg9, state.Arg10, state.Arg11, state.Arg12, state.Arg13);
                });
            });
        }
        public static Action <ILogger, TPayload, T1, T2, T3, T4, T5, Exception> DefineWithPayload <TPayload, T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string format)
        {
            var prepared = ZString.PrepareUtf8 <T1, T2, T3, T4, T5>(format);

            return((ILogger logger, TPayload payload, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception ex) =>
            {
                logger.Log(logLevel, eventId, new PreparedFormatLogState <TPayload, T1, T2, T3, T4, T5>(payload, prepared, arg1, arg2, arg3, arg4, arg5), ex, (state, _) =>
                {
                    return state.Format.Format(state.Arg1, state.Arg2, state.Arg3, state.Arg4, state.Arg5);
                });
            });
        }
示例#4
0
        public static Action <ILogger, TPayload, T1, Exception?> DefineWithPayload <TPayload, T1>(LogLevel logLevel, EventId eventId, string format)
        {
            var prepared = ZString.PrepareUtf8 <T1>(format);

            return((ILogger logger, TPayload payload, T1 arg1, Exception? ex) =>
            {
                logger.Log(logLevel, eventId, new PreparedFormatLogState <TPayload, T1>(payload, prepared, arg1), ex, (state, _) =>
                {
                    return state.Format.Format(state.Arg1);
                });
            });
        }
示例#5
0
        public static Action <ILogger, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, Exception?> Define <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(LogLevel logLevel, EventId eventId, string format)
        {
            var prepared = ZString.PrepareUtf8 <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(format);

            return((ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, Exception? ex) =>
            {
                logger.Log(logLevel, eventId, new PreparedFormatLogState <object, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(null, prepared, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11), ex, (state, _) =>
                {
                    return state.Format.Format(state.Arg1, state.Arg2, state.Arg3, state.Arg4, state.Arg5, state.Arg6, state.Arg7, state.Arg8, state.Arg9, state.Arg10, state.Arg11);
                });
            });
        }
示例#6
0
        public void Setup()
        {
            if (!GameEntity.Has <GameName>())
            {
                throw new InvalidOperationException("A game name should be set before running.");
            }

            if (Thread.CurrentThread.Name == null)
            {
                Thread.CurrentThread.Name = $"{GameEntity.Get<GameName>().Value}";
            }

            void ResolveDefaults()
            {
                if (!GameEntity.Has <GameExecutingStorage>())
                {
                    GameEntity.Set(new GameExecutingStorage(new LocalStorage(System.IO.Path.GetDirectoryName(AppContext.BaseDirectory))));
                }

                if (!GameEntity.Has <GameLoggerFactory>())
                {
                    if (GameEntity.Has <GameLogger>())
                    {
                        throw new InvalidOperationException("Game has no ILoggerFactory, but has a ILogger, either include both or none.");
                    }

                    var loggerFactory = LoggerFactory.Create(builder =>
                    {
                        static void opt(ZLoggerOptions options)
                        {
                            var prefixFormat        = ZString.PrepareUtf8 <LogLevel, DateTime, string>("[{0}, {1}, {2}] ");
                            options.PrefixFormatter = (writer, info) => prefixFormat.FormatTo(ref writer, info.LogLevel, info.Timestamp.DateTime.ToLocalTime(), info.CategoryName);
                        }

                        builder.ClearProviders();
                        builder.SetMinimumLevel(LogLevel.Debug);
                        builder.AddZLoggerRollingFile((offset, i) => $"logs/{offset.ToLocalTime():yyyy-MM-dd}_{i:000}.log",
                                                      x => x.ToLocalTime().Date,
                                                      8196,
                                                      opt);
                        builder.AddZLoggerFile("log.json");
                        try
                        {
                            Console.OutputEncoding = Encoding.UTF8;

                            builder.AddZLoggerConsole(opt);
                        }
                        catch
                        {
                            // ignored (no console)
                        }
                    });
示例#7
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
            }
        }
示例#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
            }
        }
示例#9
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>();
        });