protected override void PublishMessage(LogMessage message)
 {
     System.Console.WriteLine(
         MessageFormatter.Format(
             message,
             Options.TimeStampFormat));
 }
 protected override void PublishMessage(LogMessage message)
 {
     System.Diagnostics.Debug.WriteLine(
         MessageFormatter.Format(
             message,
             Options.TimeStampFormat));
 }
Example #3
0
        public async Task SetLanguage(string language)
        {
            var eb = new EmbedBuilder();
            var ts = await TranslationManager.CreateFor(Context.Channel);

            eb.Title = ts.GetMessage("commands/language:embed_title");

            try
            {
                CultureInfo lang = new CultureInfo(language);
                if (!TranslationManager.HasLanguage(lang))
                {
                    // Please translate :)
                    eb = EmbedFactory.CreateError()
                         .WithTitle(ts.GetMessage("commands/language:embed_title"))
                         .WithDescription(MessageFormatter.Format(ts.GetMessage("commands/language:error_language_not_found"), lang.TwoLetterISOLanguageName));
                }
                else
                {
                    eb.Color       = EmbedFactory.Success;
                    eb.Description = MessageFormatter.Format(ts.GetMessage("commands/language:language_set_message"), lang.TwoLetterISOLanguageName);
                    await TranslationManager.SetLanguageAsync(TranslationManager.GetId(Context.Channel), lang);
                }
            }
            catch (CultureNotFoundException)
            {
                eb.Description = ts.GetMessage("commands/language:error_unknown_language");
                eb.Color       = EmbedFactory.Error;
            }
            await ReplyAsync(embed : eb.Build());
        }
Example #4
0
        protected override async Task PublishMessageBatch(
            IEnumerable <LogMessage> messageBatch)
        {
            var directory = Directory.CreateDirectory(Options.Directory);

            if (!directory.Exists)
            {
                throw new DirectoryNotFoundException(
                          $"Log file directory creation failed! Maybe your application doesn't have write access to it?");
            }

            foreach (var message in messageBatch)
            {
                var path = GetLogFilePath();

                using (var stream = new FileStream(path, FileMode.Append))
                {
                    var bytes = Encoding.UTF8.GetBytes(
                        MessageFormatter.Format(
                            message,
                            Options.TimeStampFormat));

                    await stream.WriteAsync(bytes);
                }
            }

            RemoveDeprecatedFiles();
        }
Example #5
0
        public void Should_Stringify_When_OnlyUsedArguments()
        {
            var argCount = 0;

            var arg = new TestArg(parameters =>
            {
                Assert.Null(parameters);
                argCount++;
            })
            {
                Name = "arg", Value = "value"
            };

            var arg2Count = 0;
            var arg2      = new TestArg(parameters => { arg2Count++; })
            {
                Name = "arg2", Value = "value2"
            };

            var result = MessageFormatter.Format("test {arg} {arg2} {arg3}", new IMessageArg[] { arg, arg2 });

            Assert.Equal("test value value2 {arg3}", result);
            Assert.Equal(1, argCount);
            Assert.Equal(1, arg2Count);
        }
Example #6
0
        public void Should_PassParameters_When_ManyArguments()
        {
            var argCount = 0;

            var arg = new TestArg(parameters =>
            {
                Assert.Equal(3, parameters.Count);
                Assert.Equal("x", parameters["param"]);
                Assert.Equal("x2", parameters["param2"]);
                Assert.Equal("x3", parameters["param3"]);
                argCount++;
            })
            {
                Name = "arg", Value = "value", AllowedParameters = new[] { "param", "param2", "param3" }
            };

            var arg2Count = 0;

            var arg2 = new TestArg(parameters =>
            {
                Assert.Equal(1, parameters.Count);
                Assert.Equal("val", parameters["par"]);
                arg2Count++;
            })
            {
                Name = "arg2", Value = "value2", AllowedParameters = new[] { "par" }
            };

            var result = MessageFormatter.Format("test {arg|param=x|param2=x2|param3=x3} {arg2|par=val}", new IMessageArg[] { arg, arg2 });

            Assert.Equal("test value value2", result);
            Assert.Equal(1, argCount);
            Assert.Equal(1, arg2Count);
        }
 public void Format()
 {
     using (var formatter = new MessageFormatter(MessageText, "en_US"))
     {
         Assert.That(formatter.Format(2, "disk", "MyDisk"),
                     Is.EqualTo("The disk \"MyDisk\" contains 2 files."));
     }
 }
        protected override void LogMessageCore(string message, IDictionary <string, string> additionalData, Severity severity)
        {
            var sb = new StringBuilder();

            MessageFormatter.Format(message, additionalData, severity, sb);
            Console.ForegroundColor = GetColor(severity);
            Console.WriteLine(sb.ToString());
        }
Example #9
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = null;

            try
            {
                response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

                _logger.Log(_logLevel, _logMessageFormatter.Format(request, response));
            }
            catch (Exception ex)
            {
                _logger.Log(_logLevel, ex, _logMessageFormatter.Format(request, response));
                throw;
            }

            return(response);
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpResponseMessage response = null;

            try
            {
                response = await base.SendAsync(request, cancellationToken);

                logger.Log(logLevel, logMessageFormatter.Format(request, response));
            }
            catch (Exception ex)
            {
                logger.Log(logLevel, logMessageFormatter.Format(request, response, ex));
                throw ex;
            }

            return(response);
        }
Example #11
0
        public void Format_WithFormat_ShouldFormatArguments()
        {
            // Arrange
            var testee = new MessageFormatter("({0:D4})-({1:E2})-({2:F2})-({3:N2})-({4:P1})-({5:X4})");

            // Act
            var formatted = testee.Format(new object[] { 42, 42, 42, 4200, 0.42, 42 });

            // Assert
            formatted.Should().Be("(0042)-(4.20E+001)-(42.00)-(4,200.00)-(42.0 %)-(002A)");
        }
Example #12
0
        public void Format_WithNumericOutOfOrderArgs_ShouldReturnFormattedMessage()
        {
            // Arrange
            var testee = new MessageFormatter("Foo {1} {0}");

            // Act
            var formatted = testee.Format(new object[] { "baz", 42 });

            // Assert
            formatted.Should().Be("Foo 42 baz");
        }
Example #13
0
        public void Format_WithNoArgs_ShouldReturnMessage()
        {
            // Arrange
            var testee = new MessageFormatter("Foo");

            // Act
            var formatted = testee.Format(Enumerable.Empty <object>());

            // Assert
            formatted.Should().Be("Foo");
        }
Example #14
0
        public void Format_WithAllFeatures_ShouldFormatArguments()
        {
            // Arrange
            var testee = new MessageFormatter("Named {foo} Aligned {baz,4} Formatted {bar:D4} Aligned+Formatted {foobar,6:D4}");

            // Act
            var formatted = testee.Format(new object[] { "baz", 42, 42, 42 });

            // Assert
            formatted.Should().Be("Named baz Aligned   42 Formatted 0042 Aligned+Formatted   0042");
        }
Example #15
0
        public void Format_WithNamedArgs_ShouldReturnFormattedMessage()
        {
            // Arrange
            var testee = new MessageFormatter("Foo {aString} {aInt}");

            // Act
            var formatted = testee.Format(new object[] { "baz", 42 });

            // Assert
            formatted.Should().Be("Foo baz 42");
        }
Example #16
0
        public void Format_WithAlignment_ShouldAlignArguments()
        {
            // Arrange
            var testee = new MessageFormatter("({0,5})-({1,-5})");

            // Act
            var formatted = testee.Format(new object[] { "baz", 42 });

            // Assert
            formatted.Should().Be("(  baz)-(42   )");
        }
Example #17
0
        public void Format_WithMissingArg_ShouldReplaceQuestionMark()
        {
            // Arrange
            var testee = new MessageFormatter("Foo {0}");

            // Act
            var formatted = testee.Format(new object[0]);

            // Assert
            formatted.Should().Be("Foo ?");
        }
Example #18
0
        public void Format_WithEscapedBraces_ShouldReturnLiteral()
        {
            // Arrange
            var testee = new MessageFormatter("Foo {{{0}}} {{1}}");

            // Act
            var formatted = testee.Format(new object[] { "baz" });

            // Assert
            formatted.Should().Be("Foo {baz} {1}");
        }
        private async Task ProcessCommandAsync(SocketMessage arg)
        {
            // Source filter
            if (arg.Source != MessageSource.User)
            {
                return;
            }
            var message = (SocketUserMessage)arg;

            // Get the prefix
            string pfx;

            try
            {
                pfx = await GetPrefix(arg);
            }
            catch (Exception e)
            {
                string src = message.Channel is IGuildChannel gc ? $"{gc.Guild.Name} ({gc.Guild.Id})" : $"{message.Channel.Name}";
                Logger.GetLogger("Commands").Warning($"Failed to get prefix. {src}", e);
                return;
            }

            // Command check
            int argPos = 0;

            if (message.HasStringPrefix(pfx, ref argPos))
            {
                // Refresh the cached prefix
                if (message.Channel is IGuildChannel c)
                {
                    pm.RestoreCache(c.GuildId).Release();
                }
                var context = new SocketCommandContext(client, message);
                // Log message for debugging (doesn't check if the command exists)
                Logger.GetLogger("Commands").Debug($"Executing command: {GetExecutionInfo(context)}");
                // Execute command
                await commands.ExecuteAsync(context, argPos, services);
            }
            else if (message.Content.TrimEnd() == $"{pm.DefaultPrefix}prefix")
            {
                // Info
                var context = new SocketCommandContext(client, message);
                Logger.GetLogger("Commands").Debug($"Executing prefix get with default prefix: {GetExecutionInfo(context)}");
                var ts = await TranslationManager.CreateFor(context.Channel);

                message.Channel.SendMessageAsync(embed: EmbedFactory.CreateSuccess()
                                                 .WithTitle(ts.GetMessage("commands/prefix:embed_title"))
                                                 .WithDescription(MessageFormatter.Format(ts.GetMessage("commands/prefix:my_prefix_is"),
                                                                                          PrefixManagerService.PrettyPrefix(pfx)))
                                                 .Build()).Release();
            }
        }
Example #20
0
        protected override void LogMessageCore(string message, IDictionary <string, string> additionalData, Severity severity)
        {
            var sb = new StringBuilder();

            MessageFormatter.Format(message, additionalData, severity, sb);
            sb.AppendLine();

            // TODO: temporary workaround
            lock (fileWriteLock)
            {
                File.AppendAllText(GetLogFileName(), sb.ToString(), fileEncoding);
            }
        }
        public void ReturnsMessagePlusElapsedTimeOfOneSecond()
        {
            var msg = new Message(new DateTime(2000, 1, 2, 3, 4, 5), "a", "b");

            var result = sut.Format(msg, new DateTime(2000, 1, 2, 3, 4, 6));

            Assert.AreEqual("b (1 second ago)", result);
        }
        public async Task FormatMessage_with_multiple_tasks()
        {
            var pattern = "Copying {fileCount, plural, one {one file} other{# files}}.";

            // 2 with the same message to test there are no issues with caching with multiple threads.
            var t1 = Task.Run(() => MessageFormatter.Format(pattern, new { fileCount = 1 }));
            var t2 = Task.Run(() => MessageFormatter.Format(pattern, new { fileCount = 1 }));
            var t3 = Task.Run(() => MessageFormatter.Format(pattern, new { fileCount = 5 }));
            await Task.WhenAll(t1, t2);

            Assert.Equal("Copying one file.", t1.Result);
            Assert.Equal("Copying one file.", t2.Result);
            Assert.Equal("Copying 5 files.", t3.Result);
        }
Example #23
0
        /// <inheritdoc />
        public void HandleValueMismatch(string expectedValue, string actualValue, string reason, params object[] reasonArgs)
        {
            expectedValue = expectedValue ?? "match";
            actualValue   = actualValue ?? MessageFormatter.FormatValue(this.Value);

            var message = MessageFormatter.Format(
                "The {0} value shall {1}{2} but was {3}.",
                this.Name == null ? "actual" : $"'{this.Name}'",
                expectedValue,
                MessageFormatter.FormatReason(reason, reasonArgs),
                actualValue);

            throw new AssertFailedException(message);
        }
Example #24
0
        public void Should_NotPassParameters_When_ContainsInvalidParameters()
        {
            var argCount = 0;

            var arg = new TestArg(parameters => { argCount++; })
            {
                Name = "arg", Value = "value", AllowedParameters = new[] { "param" }
            };

            var result = MessageFormatter.Format("test {arg|param=x|someparameter=somevalue}", new IMessageArg[] { arg });

            Assert.Equal("test {arg|param=x|someparameter=somevalue}", result);
            Assert.Equal(0, argCount);
        }
Example #25
0
        public Translator Get(string translationName)
        {
            if (translationName == null)
            {
                throw new ArgumentNullException(nameof(translationName));
            }

            if (!Translations.TryGetValue(translationName, out var dictionary))
            {
                throw new TranslationNotFoundException(translationName);
            }

            return(error => dictionary.TryGetValue(error.Message, out var translation)
                ? MessageFormatter.Format(translation, error.Arguments)
                : MessageFormatter.Format(error.Message, error.Arguments));
        }
Example #26
0
        public void Should_ReturnSameString_When_UsingInvalidName()
        {
            var argCount = 0;

            var arg = new TestArg(parameters =>
            {
                Assert.Null(parameters);
                argCount++;
            })
            {
                Name = "arg", Value = "value"
            };

            var result = MessageFormatter.Format("test {argument}", new IMessageArg[] { arg });

            Assert.Equal("test {argument}", result);
            Assert.Equal(0, argCount);
        }
Example #27
0
        public void Should_Stringify_When_SingleVariable_ManyOccurances()
        {
            var argCount = 0;

            var arg = new TestArg(parameters =>
            {
                Assert.Null(parameters);
                argCount++;
            })
            {
                Name = "arg", Value = "value"
            };

            var result = MessageFormatter.Format("test {arg} {arg}", new IMessageArg[] { arg });

            Assert.Equal("test value value", result);
            Assert.Equal(1, argCount);
        }
Example #28
0
        protected override void EmitBatch(IEnumerable <LogEvent> events)
        {
            DB = Realm.GetInstance(Config);

            foreach (var _event in events)
            {
                var(Category, Application, Identity, ClassType, MethodName, ActivityId, ProcessId, ThreadId, Stacktrace, Properties) = Helper.ExtractEventInfo(_event);

                try
                {
                    using (var properties = new StringWriter())
                        using (var messageText = new StringWriter())
                        {
                            PropertyFormatter.Format(Properties, properties);
                            MessageFormatter.Format(_event, messageText);

                            var logMsg = new LogDBMessage
                            {
                                Timestamp       = _event.Timestamp,
                                Message         = messageText.ToString(),
                                ActivityId      = ActivityId,
                                MethodName      = MethodName,
                                ClassType       = ClassType,
                                Properties      = properties.ToString(),
                                ProcessId       = ProcessId,
                                ThreadId        = ThreadId,
                                Stacktrace      = Stacktrace,
                                MessageCategory = (short)Category,
                                MessageType     = (int)_event.Level.ToMessageType(),
                                Application     = Application,
                                Identity        = Identity,
                            };

                            DB.Write(() =>
                            {
                                DB.Add(logMsg);
                            });
                        }
                }
                catch (Exception)
                {
                }
            }
        }
Example #29
0
        public void Should_PassParameters_When_SingleParameter()
        {
            var argCount = 0;

            var arg = new TestArg(parameters =>
            {
                Assert.Equal(1, parameters.Count);
                Assert.Equal("x", parameters["param"]);
                argCount++;
            })
            {
                Name = "arg", Value = "value", AllowedParameters = new[] { "param" }
            };

            var result = MessageFormatter.Format("test {arg|param=x}", new IMessageArg[] { arg });

            Assert.Equal("test value", result);
            Assert.Equal(1, argCount);
        }
Example #30
0
        public void Format(LogEvent logEvent, TextWriter output)
        {
            try
            {
                var(Category, Application, Identity, ClassType, MethodName, ActivityId, ProcessId, ThreadId, Stacktrace, Properties) = Helper.ExtractEventInfo(logEvent);

                using (var properties = new StringWriter())
                    using (var messageText = new StringWriter())
                    {
                        MessageFormatter.Format(logEvent, messageText);
                        PropertyFormatter.Format(Properties, properties);

                        // Output the text.

                        output.WriteLine(string.Format("{0} {1} {2} {3} {4} {5} {6} {7} - {8} - {9} - {10}",
                                                       logEvent.Timestamp.ToString("dd/MM/yyyy HH:mm:ss,fff").PadRight(24),
                                                       MessageLogLevelMap[logEvent.Level].PadRight(13),
                                                       MessageCategoryMap[Category].PadRight(14),
                                                       Identity.PadRight(15),
                                                       ProcessId.ToString().PadRight(6),
                                                       ThreadId.ToString().PadRight(6),
                                                       ActivityId.PadRight(40),
                                                       ClassType,
                                                       MethodName,
                                                       messageText.ToString(),
                                                       properties.ToString()));

                        if (null != logEvent.Exception)
                        {
                            output.Write(logEvent.Exception.ToFormattedString());
                        }

                        if (!String.IsNullOrWhiteSpace(Stacktrace))
                        {
                            output.WriteLine(Stacktrace);
                        }
                    }
            }
            catch (Exception)
            {
            }
        }