public void WellKnownSpecialCharactersAreEscapedAsNormal()
        {
            const string s       = "\\\"\t\r\n\f";
            var          escaped = SimpleJsonFormatter.Escape(s);

            Assert.AreEqual("\\\\\\\"\\t\\r\\n\\f", escaped);
        }
Exemple #2
0
        /// <summary>
        /// Emit a batch of log events, running to completion synchronously.
        /// </summary>
        /// <param name="events">The events to emit.</param>
        /// <remarks>Override either <see cref="PeriodicBatchingSink.EmitBatch"/> or <see cref="PeriodicBatchingSink.EmitBatchAsync"/>,
        /// not both.</remarks>
        protected override void EmitBatch(IEnumerable <LogEvent> events)
        {
            var payload = new StringWriter();

            payload.Write("{\"d\":[");

            var formatter  = new SimpleJsonFormatter(true);
            var delimStart = "{";

            foreach (var logEvent in events)
            {
                payload.Write(delimStart);
                formatter.Format(logEvent, payload);
                var renderedMessage = logEvent.RenderedMessage;
                payload.Write(",\"UtcTimestamp\":\"{0:u}\",\"RenderedMessage\":\"{1}\"}}",
                              logEvent.Timestamp.ToUniversalTime().DateTime,
                              SimpleJsonFormatter.Escape(renderedMessage));
                delimStart = ",{";
            }

            payload.Write("]}");

            var bson = BsonDocument.Parse(payload.ToString());
            var docs = bson["d"].AsBsonArray;

            GetLogCollection().InsertBatch(docs);
        }
Exemple #3
0
        /// <summary>
        /// Emit a batch of log events, running asynchronously.
        /// </summary>
        /// <param name="events">The events to emit.</param>
        /// <remarks>Override either <see cref="PeriodicBatchingSink.EmitBatch"/> or <see cref="PeriodicBatchingSink.EmitBatchAsync"/>,
        /// not both.</remarks>
        protected override async Task EmitBatchAsync(IEnumerable <LogEvent> events)
        {
            var payload = new StringWriter();

            payload.Write("{\"docs\":[");

            var formatter  = new SimpleJsonFormatter(true);
            var delimStart = "{";

            foreach (var logEvent in events)
            {
                payload.Write(delimStart);
                formatter.Format(logEvent, payload);
                var renderedMessage = logEvent.RenderedMessage;
                payload.Write(",\"UtcTimestamp\":\"{0:u}\",\"RenderedMessage\":\"{1}\"}}",
                              logEvent.Timestamp.ToUniversalTime().DateTime,
                              SimpleJsonFormatter.Escape(renderedMessage));
                delimStart = ",{";
            }

            payload.Write("]}");

            var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
            var result  = await _httpClient.PostAsync(BulkUploadResource, content);

            if (!result.IsSuccessStatusCode)
            {
                SelfLog.WriteLine("Received failed result {0}: {1}", result.StatusCode, result.Content.ReadAsStringAsync().Result);
            }
        }
        public void EmbeddedEscapesPreservePrefixAndSuffix()
        {
            const string s       = "a\nb";
            var          escaped = SimpleJsonFormatter.Escape(s);

            Assert.AreEqual("a\\nb", escaped);
        }
        public void UnprintableCharactersAreEscapedAsUnicodeSequences()
        {
            const string s       = "\u0001";
            var          escaped = SimpleJsonFormatter.Escape(s);

            Assert.AreEqual("\\u0001", escaped);
        }
        public void StringsWithoutSpecialCharactersAreUnchanged()
        {
            const string s       = "Hello, world!";
            var          escaped = SimpleJsonFormatter.Escape(s);

            Assert.AreSame(s, escaped);
        }
        /// <summary>
        /// Rebuilt default language file
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static bool RebuiltDefaultLanguage(string filename)
        {
            bool ret = false;

            //get text from all classes
            IDictionary <string, string> defaultlanguage = GetAllLanguages();

            //write text to file
            if (!String.IsNullOrEmpty(filename))
            {
                //serialize the list
                try
                {
#if NETFRAMEWORK
                    string jsontext = new SimpleJsonFormatter(new JavaScriptSerializer().Serialize(defaultlanguage)).Format();
#else
                    string jsontext = new SimpleJsonFormatter(JsonSerializer.Serialize(defaultlanguage)).Format();
#endif
                    File.WriteAllText(filename, jsontext, Encoding.UTF8);
                    ret = true;
                }
                catch { }
            }

            return(ret);
        }
Exemple #8
0
        async Task OnTick()
        {
            var      count  = 0;
            var      events = new Queue <LogEvent>();
            LogEvent next;

            while (count < MaxPost && _queue.TryDequeue(out next))
            {
                count++;
                events.Enqueue(next);
            }

            if (events.Count == 0)
            {
                return;
            }

            var payload = new StringWriter();

            payload.Write("{\"docs\":[");

            var formatter  = new SimpleJsonFormatter(true);
            var delimStart = "{";

            foreach (var logEvent in events)
            {
                payload.Write(delimStart);
                formatter.Format(logEvent, payload);
                var renderedMessage = logEvent.RenderedMessage;
                payload.Write(",\"UtcTimeStamp\":\"{0:u}\",\"RenderedMessage\":\"{1}\"}}",
                              logEvent.TimeStamp.ToUniversalTime().DateTime,
                              renderedMessage);
                delimStart = ",{";
            }

            payload.Write("]}");

            try
            {
                var content = new StringContent(payload.ToString(), Encoding.UTF8, "application/json");
                var result  = await _httpClient.PostAsync(BulkUploadResource, content);

                if (!result.IsSuccessStatusCode)
                {
                    SelfLog.WriteLine("Received failed result {0}: {1}", result.StatusCode, result.Content.ReadAsStringAsync().Result);
                }
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch { }
            // ReSharper restore EmptyGeneralCatchClause
            finally
            {
                if (!_unloading)
                {
                    SetTimer();
                }
            }
        }
Exemple #9
0
        void OnTick()
        {
            var      count  = 0;
            var      events = new Queue <LogEvent>();
            LogEvent next;

            while (count < MaxPost && _queue.TryDequeue(out next))
            {
                count++;
                events.Enqueue(next);
            }

            if (events.Count == 0)
            {
                return;
            }

            var payload = new StringWriter();

            payload.Write("{\"d\":[");

            var formatter  = new SimpleJsonFormatter(true);
            var delimStart = "{";

            foreach (var logEvent in events)
            {
                payload.Write(delimStart);
                formatter.Format(logEvent, payload);
                var renderedMessage = logEvent.RenderedMessage;
                payload.Write(",\"UtcTimeStamp\":\"{0:u}\",\"RenderedMessage\":\"{1}\"}}",
                              logEvent.TimeStamp.ToUniversalTime().DateTime,
                              renderedMessage);
                delimStart = ",{";
            }

            payload.Write("]}");

            try
            {
                var bson = BsonDocument.Parse(payload.ToString());
                var docs = bson["d"].AsBsonArray;
                LogCollection.InsertBatch(docs);
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch { }
            // ReSharper restore EmptyGeneralCatchClause
            finally
            {
                if (!_unloading)
                {
                    SetTimer();
                }
            }
        }
        static dynamic FormatJson(LogEvent @event)
        {
            var formatter = new SimpleJsonFormatter();
            var output    = new StringWriter();

            formatter.Format(@event, output);

            var serializer = new JsonSerializer {
                DateParseHandling = DateParseHandling.None
            };

            return(serializer.Deserialize(new JsonTextReader(new StringReader(output.ToString()))));
        }
            /// <summary>
            /// Write all language text load to file
            /// </summary>
            /// <param name="filename"></param>
            /// <returns></returns>
            public bool WriteToFile(string filename)
            {
                bool ret = false;

                IDictionary <string, string> language = Get();

                if (!String.IsNullOrEmpty(filename))
                {
                    //serialize the list
                    try
                    {
                        string jsontext = new SimpleJsonFormatter(new JavaScriptSerializer().Serialize(language)).Format();
                        File.WriteAllText(filename, jsontext, Encoding.UTF8);
                        ret = true;
                    }
                    catch { }
                }

                return(ret);
            }
        /// <summary>
        /// Check a language file against default values
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="removeNotNeeded"></param>
        /// <param name="messages"></param>
        /// <returns></returns>
        public static bool RebuiltLanguage(string filename, bool removeNotNeeded, ref string[] messages)
        {
            bool ret = false;

            messages = new string[] { };

            IDictionary <string, string> rebuiltlanguage = new Dictionary <string, string>();

            //get text from all classes
            IDictionary <string, string> defaultlanguage = GetAllLanguages();

            //get text from language file
            IDictionary <string, string> loadedlanguage = new Dictionary <string, string>();

            //read text from file
            if (!String.IsNullOrEmpty(filename))
            {
                //deserialize the file
                try
                {
                    string jsontext = File.ReadAllText(filename);
#if NETFRAMEWORK
                    loadedlanguage = new JavaScriptSerializer().Deserialize <Dictionary <string, string> >(jsontext);
#else
                    loadedlanguage = JsonSerializer.Deserialize <Dictionary <string, string> >(jsontext);
#endif
                    ret = true;
                }
                catch { }
            }

            //check the languages
            foreach (KeyValuePair <string, string> entry in defaultlanguage)
            {
                //add the existing key
                if (loadedlanguage.ContainsKey(entry.Key))
                {
                    rebuiltlanguage.Add(entry.Key, loadedlanguage[entry.Key]);
                }
                //add not existing key
                else
                {
                    rebuiltlanguage.Add(entry.Key, defaultlanguage[entry.Key]);
                    messages = messages.Concat(new string[] { "Text \"" + entry.Key + "\" not found. Added using default value." }).ToArray();
                }
            }
            foreach (KeyValuePair <string, string> entry in loadedlanguage)
            {
                //remove not existing key
                if (!defaultlanguage.ContainsKey(entry.Key))
                {
                    if (removeNotNeeded)
                    {
                        messages = messages.Concat(new string[] { "Text \"" + entry.Key + "\" not needed. Removed." }).ToArray();
                    }
                    else
                    {
                        rebuiltlanguage.Add(entry.Key, loadedlanguage[entry.Key]);
                        messages = messages.Concat(new string[] { "Text \"" + entry.Key + "\" not needed. Not removed." }).ToArray();
                    }
                }
            }

            //write text to file
            if (!String.IsNullOrEmpty(filename))
            {
                //serialize the list
                try
                {
#if NETFRAMEWORK
                    string jsontext = new SimpleJsonFormatter(new JavaScriptSerializer().Serialize(rebuiltlanguage)).Format();
#else
                    string jsontext = new SimpleJsonFormatter(JsonSerializer.Serialize(rebuiltlanguage)).Format();
#endif
                    File.WriteAllText(filename, jsontext, Encoding.UTF8);
                    ret = true;
                }
                catch { }
            }

            return(ret);
        }