예제 #1
0
        /// <summary>
        /// 记录用户操作日志
        /// </summary>
        /// <param name="context">日志上下文</param>
        public static void LogOperation(LogContext context)
        {
            try
            {
                Logger logger = NLog.LogManager.GetLogger("Operation");

                if (ConfigurationManager.LoggingEnable && logger.IsInfoEnabled)
                {
                    LogEventInfo log = new LogEventInfo(LogLevelConverter.Convert(context.Level), "", "");

                    log.Properties["type"] = context.Type;
                    log.Properties["url"] = context.RequestUrl;
                    log.Properties["referer"] = context.RefererUrl;
                    log.Properties["controller"] = context.Controller;
                    log.Properties["action"] = context.Action;
                    log.Properties["username"] = context.Username;
                    log.Properties["userip"] = context.UserIP;
                    log.Properties["useragent"] = context.UserAgent;
                    log.Message = context.Message;
                    log.TimeStamp = context.TimeStamp;

                    logger.Log(log);
                }
            }
            catch { }
        }
예제 #2
0
 public override void Flush(LogContext context)
 {
   var msg = Format(context.Logger, context);
   if (!String.IsNullOrEmpty(msg))
   {
     Debug.Print(msg);
   }
 }
예제 #3
0
        public void returns_only_tokens_for_empty_and_nulls(string p)
        {
            var ctx = new LogContext();
            string result = ctx.Tokenize(p);

            Assert.Equal('[', result[0]);
            Assert.DoesNotThrow(() => Guid.Parse(result.Substring(1, _guidLength)));
            Assert.Equal(']', result[result.Length - 1]);
        }
예제 #4
0
 public override void Flush(LogContext context)
 {
   var msg = Format(context.Logger, context);
   if (String.IsNullOrEmpty(msg))
     return;
   var sw = GetWriter(context.Logger);
   sw.WriteLine(msg);
   sw.Flush();
 }
예제 #5
0
        public void does_not_break_strings_that_contain_format_placeholders()
        {
            var ctx = new LogContext();

            string formatInput = "abc {0}def {1} xyz";

            string result = ctx.Tokenize(formatInput).FormatWith("11", "22");

            Assert.Equal("abc 11def 22 xyz", result.Substring(0, result.Length - (5 + _guidLength)));
        }
 public void Set(object fromKey, IEnumerable toKeys)
 {
     var oldToKeys = GetToKeys(fromKey);
     RelationEditor.Set(fromKey, toKeys);
     var logContext = new LogContext() {
         FromKey = fromKey,
         RelationName = RelationName,
         AddedToKeys = toKeys.Cast<object>().Where( toKey => !DalcRelationEditor.Contains(toKey, oldToKeys)).ToArray(),
         RemovedToKeys = oldToKeys.Cast<object>().Where(oldToKey => !DalcRelationEditor.Contains(oldToKey, toKeys)).ToArray()
     };
     WriteLog.Execute(logContext);
 }
        public void strings_generated_later_have_higher_timespan()
        {
            string str = Randomizer.String();

            var ctx = new LogContext();

            string result1 = ctx.TokenizeTime(str);
            Thread.Sleep(100);
            string result2 = ctx.TokenizeTime(str);

            TimeSpan time1 = TimeSpan.ParseExact(result1.Substring(1, _timespanLength), TimeSpanExtensions.FORMAT, null);
            TimeSpan time2 = TimeSpan.ParseExact(result2.Substring(1, _timespanLength), TimeSpanExtensions.FORMAT, null);

            Assert.True(time2 > time1);
        }
        public void prepends_generated_strings_with_timespan()
        {
            string str = Randomizer.String();

            var ctx = new LogContext();

            string result = ctx.TokenizeTime(str);

            Assert.Equal('[', result[0]);

            string time = result.Substring(1, _timespanLength);
            Assert.DoesNotThrow(() => TimeSpan.ParseExact(time, TimeSpanExtensions.FORMAT, null));

            Assert.Equal(']', result[_timespanLength + 1]);
            Assert.Equal(' ', result[_timespanLength + 2]);
        }
예제 #9
0
        public void uses_format_to_inject_timespan_in_strings()
        {
            string str = Randomizer.String();

            var ctx = new LogContext("{elapsed} [x] {message}");

            string result = ctx.Format(str);

            string time = result.Substring(0, _timespanLength);
            Assert.DoesNotThrow(() => TimeSpan.ParseExact(time, TimeSpanExtensions.FORMAT, null));

            string x = result.Substring(time.Length, 5);
            Assert.Equal(" [x] ", x);

            string msg = result.Substring(time.Length + x.Length);
            Assert.Equal(str, msg);
        }
예제 #10
0
        public void uses_format_to_inject_guid_in_strings()
        {
            string str = Randomizer.String();

            var ctx = new LogContext("{token} [x] {message}");

            string result = ctx.Format(str);

            string token = result.Substring(0, _guidLength);
            Assert.DoesNotThrow(() => Guid.Parse(token));

            string x = result.Substring(token.Length, 5);
            Assert.Equal(" [x] ", x);

            string msg = result.Substring(token.Length + x.Length);
            Assert.Equal(str, msg);
        }
예제 #11
0
 public void TestKeyReservationErrors()
 {
     lock (_keyReservations)
     {
         _keyReservations.Clear();
         _prefixReservations.Clear();
     }
     Guid reservation = Guid.NewGuid();
     string key = Tester.RandomGenerator.RandomString(LogContext.MaximumKeyLength);
     string key2 = LogContext.ReserveKey(key, reservation);
     Assert.AreEqual(key, key2);
     Guid r2;
     Assert.IsTrue(_keyReservations.TryGetValue(key, out r2));
     Assert.AreEqual(reservation, r2);
     string value = Tester.RandomGenerator.RandomString();
     LogContext context = new LogContext();
     context.Set(key,value);
 }
예제 #12
0
        public void one_instance_uses_one_guid_for_all_strings()
        {
            string str1 = Randomizer.String();
            string str2 = Randomizer.String();

            var ctx = new LogContext();

            string result1 = ctx.Tokenize(str1);
            string result2 = ctx.Tokenize(str2);
            string result3 = ctx.Tokenize(str2);

            Guid token1 = Guid.Parse(result1.Substring(str1.Length + 4, _guidLength));
            Guid token2 = Guid.Parse(result2.Substring(str2.Length + 4, _guidLength));

            Assert.Equal(token1, token2);

            Assert.Equal(result2, result3);
        }
예제 #13
0
 protected String Format(String logger, LogContext context)
 {
   var msg = "";
   switch (context.Level)
   {
     case LogLevel.DEBUG:
       msg = String.Format(Setting.Formatter.PatternDebug, context.LoggedTime, context.ThreadName, logger, context.message);
       break;
     case LogLevel.WARN:
       msg = String.Format(Setting.Formatter.PatternWarn, context.LoggedTime, context.ThreadName, logger, context.message);
       break;
     case LogLevel.ERROR:
       msg = String.Format(Setting.Formatter.PatternError, context.LoggedTime, context.ThreadName, logger, context.message);
       break;
     default:
       break;
   }
   return msg;
 }
예제 #14
0
        public void does_not_break_strings_that_contain_format_placeholders()
        {
            var ctx = new LogContext("prefix {message} middle {elapsed} | {token} suffix");

            string formatInput = "abc {0}def {1} xyz";

            string result = ctx.Format(formatInput).FormatWith("11", "22");

            string expectedStart = "prefix abc 11def 22 xyz middle ";

            Assert.True(result.StartsWith(expectedStart));

            Assert.DoesNotThrow(() => TimeSpan.ParseExact(result.Substring(expectedStart.Length, _timespanLength), TimeSpanExtensions.FORMAT, null));

            Assert.Equal(" | ", result.Substring(expectedStart.Length + _timespanLength, 3));

            Assert.DoesNotThrow(() => Guid.Parse(result.Substring(expectedStart.Length + _timespanLength + 3, _guidLength)));

            Assert.True(result.EndsWith(" suffix"));
        }
예제 #15
0
 public void TestKeyReservation()
 {
     lock (_keyReservations)
     {
         _keyReservations.Clear();
         _prefixReservations.Clear();
     }
     Guid reservation = Guid.NewGuid();
     string key = "My test key";
     string key2 = LogContext.ReserveKey(key, reservation);
     Assert.AreEqual(key, key2);
     Guid r2;
     Assert.IsTrue(_keyReservations.TryGetValue(key, out r2));
     Assert.AreEqual(reservation, r2);
     string value = Tester.RandomGenerator.RandomString();
     LogContext context = new LogContext();
     context.Set(reservation, key, value);
     Assert.IsNotNull(context);
     string value2 = context.Get(key);
     Assert.AreEqual(value, value2);
 }
예제 #16
0
        public void appends_pipe_with_guid_to_generated_strings()
        {
            string str = Randomizer.String();

            var ctx = new LogContext();

            string result = ctx.Tokenize(str);

            string beforeToken = result.Substring(0, str.Length);
            Assert.Equal(str, beforeToken);

            Assert.Equal(' ', result[str.Length]);

            Assert.Equal('|', result[str.Length + 1]);
            Assert.Equal(' ', result[str.Length + 2]);

            Assert.Equal('[', result[str.Length + 3]);

            string token = result.Substring(str.Length + 4, _guidLength);
            Assert.DoesNotThrow(() => Guid.Parse(token));

            Assert.Equal(']', result[str.Length + 3 + _guidLength + 1]);
        }
예제 #17
0
		/// <summary>
		/// Query KhronoApi derived class enumeration names.
		/// </summary>
		/// <param name="khronoApiType">
		/// A <see cref="Type"/> that specifies the type of the class where to query enumeration names.
		/// </param>
		/// <returns>
		/// It returns a <see cref="Dictionary{Int32, String}"/> that correlates the enumeration value with
		/// the enumeration name.
		/// </returns>
		protected static LogContext QueryLogContext(Type khronoApiType)
		{
			if (khronoApiType == null)
				throw new ArgumentNullException("khronoApiType");

			LogContext logContext = new LogContext();

			Dictionary<Int64, string> enumNames = new Dictionary<Int64, string>();
			Dictionary<string, Dictionary<Int64, string>> enumBitmasks = new Dictionary<string, Dictionary<Int64, string>>();

			FieldInfo[] fieldInfos = khronoApiType.GetFields(BindingFlags.Public | BindingFlags.Static);

			foreach (FieldInfo fieldInfo in fieldInfos) {
				// Enumeration values are defined as const fields
				if (fieldInfo.IsLiteral == false)
					continue;

				// Enumeration values have at least one RequiredByFeatureAttribute
				Attribute[] requiredByFeatureAttribs = Attribute.GetCustomAttributes(fieldInfo, typeof(RequiredByFeatureAttribute));
				if ((requiredByFeatureAttribs == null) || (requiredByFeatureAttribs.Length == 0))
					continue;

				LogAttribute logAttribute = (LogAttribute)Attribute.GetCustomAttribute(fieldInfo, typeof(LogAttribute));
				IConvertible fieldInfoValue = (IConvertible)fieldInfo.GetValue(null);
				Int64 enumValueKey = fieldInfoValue.ToInt64(System.Globalization.NumberFormatInfo.InvariantInfo);

				// Pure enum
				if ((logAttribute == null) || (logAttribute.BitmaskName == null)) {
					// Collect enumeration
					if (enumNames.ContainsKey(enumValueKey) == false)
						enumNames.Add(enumValueKey, fieldInfo.Name);
				}

				// Bitmask enum
				if ((logAttribute != null) && (logAttribute.BitmaskName != null)) {
					Dictionary<Int64, string> enumBitmaskNames;

					if (enumBitmasks.TryGetValue(logAttribute.BitmaskName, out enumBitmaskNames) == false) {
						enumBitmaskNames = new Dictionary<long, string>();
						enumBitmasks.Add(logAttribute.BitmaskName, enumBitmaskNames);
					}

					if (enumBitmaskNames.ContainsKey(enumValueKey) == false)
						enumBitmaskNames.Add(enumValueKey, fieldInfo.Name);
				}
			}

			// Componse LogContext
			logContext.EnumNames = enumNames;
			logContext.EnumBitmasks = enumBitmasks;

			return (logContext);
		}
예제 #18
0
        public async Task TestMemoryLogger()
        {
            Log.CacheMaximum = 1000;
            Log.CacheExpiry = TimeSpan.FromMinutes(1);
            Log.ValidLevels = LoggingLevels.All;

            string message = "Test message " + Guid.NewGuid();
            LogContext context = new LogContext();
            context.Set("My data", 1);
            context.Set("Some more", "Test");
            Log.Add(context, LoggingLevel.Notification, message);
            await Log.Flush();

            List<Log> logs = Log.AllCached.ToList();
            Assert.IsNotNull(logs);
            Assert.IsTrue(logs.Any(), "No logs found!");
            Assert.IsTrue(logs.Any(l => l.Message == message), "No log with the message '{0}' found.", message);
        }
예제 #19
0
 public void Push(LogContext context)
 {
   Queue.Enqueue(context);
 }
예제 #20
0
 static internal void LogOperationalError(PSEventId id, PSOpcode opcode, PSTask task, LogContext logContext, string payLoad) { }
예제 #21
0
 public virtual void Flush(LogContext context)
 {
   throw new NotImplementedException();
 }