示例#1
0
        /// <summary>
        /// Logs a message with the specified <see cref="TraceLevel"/>.
        /// Default <see cref="TraceLevel"/> is <see cref="TraceLevel.Info"/>
        /// </summary>
        /// <param name="message">The message to log</param>
        /// <param name="traceLevel">The trace to write to</param>
        public static void Log(string message, TraceLevel traceLevel = TraceLevel.Info)
        {
            switch (traceLevel)
            {
            case TraceLevel.Info:
                Trace.WriteLine(message, traceLevel.ToString());
                break;

            case TraceLevel.Warning:
                Trace.WriteLine(message, traceLevel.ToString());
                break;

            case TraceLevel.Error:
                Trace.WriteLine(message, traceLevel.ToString());
                break;

            case TraceLevel.Verbose:
                Trace.WriteLine(message, traceLevel.ToString());
                break;

            case TraceLevel.Off:
            default:
                break;
            }
        }
示例#2
0
 public void Log(TraceLevel severity, string className, string message, Exception exception)
 {
     if (exception == null)
     {
         ThriftLog.Info($"Zookeeper {severity.ToString()} {className} {message} ");
     }
     else
     {
         ThriftLog.Info($"Zookeeper {severity.ToString()} {className} {message} {exception.Message} {exception.StackTrace}");
     }
 }
示例#3
0
        private string GetSectionPrefix(TraceLevel traceLevel)
        {
            const int fixedLengthTraceLevel = 7;
            var       postFixLength         = fixedLengthTraceLevel - traceLevel.ToString().Length;
            var       strTrcLvl             = traceLevel.ToString().PadRight(postFixLength);

            var prefix = string.Format("[{0}] ", strTrcLvl);

            for (var i = 0; i < _indentLevel; i++)
            {
                prefix += LEVEL_INDICATOR;
            }
            return(prefix);
        }
示例#4
0
 private void writeLog(TraceLevel level, string value)
 {
     if (level <= this.Level && textBox != null)
     {
         textBox.AppendText(DateTime.Now + " " + level.ToString() + ": " + value + "\r\n");
         textBox.Refresh();
     }
     if (level <= this.Level && logStream != null)
     {
         byte[] ss = Encoding.ASCII.GetBytes(DateTime.Now + " " + level.ToString() + ": " + value + "\r\n");
         logStream.Write(ss, 0, ss.Length);
         logStream.Flush();
     }
     Trace.WriteLineIf(level <= this.Level, DateTime.Now + " " + level.ToString() + ": " + value);
 }
示例#5
0
        /// <summary>
        /// Writes the specified trace level, message and optional exception.
        /// </summary>
        /// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
        /// <param name="message">The trace message.</param>
        /// <param name="ex">The trace exception. This parameter is optional.</param>
        public void Trace(TraceLevel level, string message, Exception?ex)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(
                DateTime.Now.ToString(
                    "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff",
                    CultureInfo.InvariantCulture
                    )
                );
            sb.Append(" ");
            sb.Append(level.ToString("g"));
            sb.Append(" ");
            sb.Append(message);

            string s = sb.ToString();

            lock (_lock)
            {
                if (_traceMessages.Count >= 1000)
                {
                    _traceMessages.Dequeue();
                }

                _traceMessages.Enqueue(s);
            }
        }
示例#6
0
 public void Log(string message, TraceLevel level)
 {
     using (StreamWriter writer = File.AppendText(fileName + ".log"))
     {
         writer.WriteLine(message + "\t" + level.ToString() + "\t" + DateTime.Now);
     }
 }
示例#7
0
        /// <summary>
        /// Logs message to underlying loggers.
        /// </summary>
        /// <param name="callInfo">The call information.</param>
        /// <param name="traceLevel">The trace level.</param>
        /// <param name="message">The message.</param>
        private static void Log(CallInfo callInfo, TraceLevel traceLevel, string message)
        {
            string messageToLog = callInfo.ToString() + " -- " + traceLevel.ToString() + " -- " + message;

            Console.WriteLine(messageToLog);
            telemetryClient.TrackTrace(messageToLog);
        }
示例#8
0
        internal static void TraceOut(TraceLevel level, string text, string category, int indent)
        {
            if (
                level.Equals(TraceLevel.Error) && TcPluginTraceSwitch.TraceError ||
                level.Equals(TraceLevel.Warning) && TcPluginTraceSwitch.TraceWarning ||
                level.Equals(TraceLevel.Info) && TcPluginTraceSwitch.TraceInfo ||
                level.Equals(TraceLevel.Verbose) && TcPluginTraceSwitch.TraceVerbose
                )
            {
                var timeStr = GetTraceTimeString();
                if (indent < 0 && Trace.IndentLevel > 0)
                {
                    Trace.IndentLevel--;
                }

                var levelStr = level.ToString()
                               .Replace("Verbose", "Debug")
                               .Replace("Warning", "Warn ")
                               .Replace("Info", "Info ");

                Trace.WriteLine($"[A{AppDomain.CurrentDomain.Id}|T{Thread.CurrentThread.ManagedThreadId}] {text}", timeStr + " - " + levelStr + " - " + category);

                if (indent > 0)
                {
                    Trace.IndentLevel++;
                }
            }
        }
示例#9
0
        private void LoggerWriteLine(int indent, TraceLevel level, string line, IReadOnlyList <KeyValuePair <string, object> > logState = null, Exception exception = null, bool labels = false)
        {
            if (level != TraceLevel.Off && labels)
            {
                var color = level switch
                {
                    TraceLevel.Warning => ConsoleColor.Yellow,
                    TraceLevel.Error => ConsoleColor.Red,
                    _ => ConsoleColor.Green,
                };

                var levelStr = level.ToString();

                this.IO.Writer.Write("[");
                this.WriteAsColor(levelStr, color);
                this.IO.Writer.Write("] ".PadRight(9 - levelStr.Length));
            }

            var shift = string.Join("", Enumerable.Repeat(' ', indent * 2));

            this.IO.Writer.Write(shift);

            var index = -1;

            for (var i = 0; i < line.Length; i++)
            {
                if (line[i] == '{')
                {
                    index = i;
                    continue;
                }

                if (line[i] == '}')
                {
                    var substr = line[index..i].Replace("{", "").Replace("}", "");
示例#10
0
        private void Log(string message, TraceLevel level)
        {
            if (level == TraceLevel.Warning)
            {
                Trace.TraceWarning(message);
            }
            else if (level == TraceLevel.Error)
            {
                Trace.TraceError(message);
            }
            else
            {
                Trace.TraceInformation(message);
            }

            if (ConsoleOutput)
            {
                Console.WriteLine(message);
            }

            if (!Directory.Exists(LogDirectory))
            {
                Directory.CreateDirectory(LogDirectory);
            }

            var logEntry = string.Format("[{0} {1}][{2}]: {3}\r\n",
                                         DateTime.Now.ToString("yyyy-MM-dd"),
                                         DateTime.Now.ToString("hh:mm:sstt"),
                                         level.ToString().ToUpper(), message);

            File.AppendAllText(LogFile, logEntry);
        }
示例#11
0
 public void Trace(TraceLevel level, string message, Exception ex)
 {
     if (level <= LevelFilter)
     {
         _output.WriteLine("{0}: {1}", level.ToString(), message);
     }
 }
示例#12
0
        public override void Log(TraceLevel level, object value, [CallerMemberName] string methodName = null)
        {
            if ((int)MaximumTraceLevel < (int)level)
            {
                return;
            }

            var msg = string.Format("{0}", value).Nullify();

            if (msg != null)
            {
                msg = DateTime.Now + " | " + msg;
            }

            if (LogToConsole)
            {
                base.Log(level, value, methodName);
            }

            if (msg != null && LogToFile)
            {
                Task.Factory.StartNew(() =>
                {
                    using (var writer = new StreamWriter(FilePath, true, Encoding.UTF8))
                    {
                        writer.WriteLine(level.ToString().PadRight(7) + " | #" + _counter + " | T" + Thread.CurrentThread.ManagedThreadId + " | " + msg);
                        writer.Flush();
                        _counter++;
                    }
                }, CancellationToken.None, TaskCreationOptions.None, _scheduler);
            }
        }
示例#13
0
        private void loglevelMenuItem_Click(object sender, RoutedEventArgs e)
        {
            try {
                // update UI
                TraceLevel level = TraceLevel.Error;
                foreach (var pair in this.logLevelMenuItemGroup)
                {
                    if (pair.Item1 == sender)
                    {
                        pair.Item1.IsChecked = true;
                        level = pair.Item2;
                    }
                    else
                    {
                        pair.Item1.IsChecked = false;
                    }
                }

                this.levelValueLabel.Content = level.ToString();

                // set log level
                Logger.LogLevel = level;
            } catch (Exception exception) {
                ErrorMessage(exception.Message);
            }
        }
示例#14
0
        public static void Log(TraceLevel loglevel, string type, string message, string user, string host)
        {
            OdbcConnection con = new OdbcConnection(ConfigurationManager.ConnectionStrings["MASTERDB2LOCAL"].ConnectionString);

            try
            {
                string query = string.Format("INSERT INTO AB_WEB_LOGS (LOGLEVEL, APPLICATIONNAME, LOGTYPENAME, THREAD, USERNAME, MACHINE, MESSAGE, AUDITTIMESTAMP) "

                                             + " VALUES('{0}','{1}','{2}','{3}','{4}','{5}', '{6}' , CURRENT TIMESTAMP)",
                                             loglevel.ToString(),
                                             "Multilinhas",
                                             type,
                                             HttpContext.Current.Session.SessionID,
                                             user, host, message);

                OdbcDataAdapter ad = new OdbcDataAdapter();
                con.Open();
                ad.InsertCommand = new OdbcCommand(query, con);
                ad.InsertCommand.ExecuteNonQuery();
                con.Dispose();
            }
            catch
            {
                //throw new Exception(ex.Message);
            }
        }
        public FileLogTraceWriter(TraceLevel traceLevel, string sectionTitle)
        {
            _traceLevel = traceLevel;
            fileName    = "JsonNETTraceLog" + "-" + _traceLevel.ToString() + ".log";
            string text = "*** " + sectionTitle + ": " + traceLevel.ToString() + " ***" + Environment.NewLine;

            System.IO.File.AppendAllText(fileName, text);
        }
 /// <summary>
 /// Constructs a new instance.
 /// </summary>
 /// <param name="window">The duration of the sliding window.</param>
 /// <param name="threshold">The maximum number of matching trace messages to allow before triggering a notification.</param>
 /// <param name="filter">The optional event filter to apply on each <see cref="TraceEvent"/>.</param>
 /// <param name="message">The optional message to use for notifications.</param>
 /// <param name="level">The maximum trace level of trace messages that will match the filter.</param>
 public SlidingWindowTraceFilter(TimeSpan window, int threshold, Func<TraceEvent, bool> filter = null, string message = null, TraceLevel level = TraceLevel.Error)
 {
     _window = window;
     _level = level;
     Threshold = threshold;
     _filter = filter;
     _notificationMessage = message ?? string.Format("{0} events at level '{1}' or lower have occurred within time window {2}.", threshold, level.ToString(), _window);
 }
示例#17
0
        }         // Logger

        // ----------------------------------------------------------------------
        private void Log(TraceLevel logLevel, object message, Exception exception)
        {
            if (!IsSupportedException(exception))
            {
                return;
            }

            if (level.Level >= logLevel)
            {
                StringBuilder buf = new StringBuilder(name);
                buf.Append(": ");
                switch (logLevel)
                {
                case TraceLevel.Off:
                    buf.Append("Fatal");
                    break;

                case TraceLevel.Verbose:
                    buf.Append("Debug");
                    break;

                default:
                    buf.Append(logLevel.ToString());
                    break;
                }
                buf.Append(": ");
                if (message != null)
                {
                    buf.Append(message);
                }
                if (exception != null)
                {
                    buf.Append(": ");
                    buf.Append(exception.ToString());
                }
                switch (logLevel)
                {
                case TraceLevel.Off:                         // used by 'fatal'
                case TraceLevel.Error:
                    Trace.TraceError(buf.ToString());
                    break;

                case TraceLevel.Warning:
                    Trace.TraceWarning(buf.ToString());
                    break;

                case TraceLevel.Info:
                    goto default;

                case TraceLevel.Verbose:
                    goto default;

                default:
                    Trace.TraceInformation(buf.ToString());
                    break;
                }
            }
        }         // Log
        public void SettingTraceLevelTo(TraceLevel level)
        {
            var target = new Parameters {
                Trace = level
            };
            var expected = " /trace:" + level.ToString().ToLower();

            target.ToString().Should().Be(expected);
        }
示例#19
0
        public void Message(TraceLevel level, string text, string source, TextPosition position)
        {
            if (string.IsNullOrEmpty(source))
            {
                Console.Error.WriteLine($"Twofold: {level.ToString()}: {text}");
                Trace.WriteLine($"Twofold: {level.ToString()}: {text}");
                return;
            }

            string positionText = "";

            if (position.IsValid)
            {
                positionText = position.ToString();
            }
            Console.Error.WriteLine($"{source}{positionText}: {level.ToString()}: {text}");
            Trace.WriteLine($"{source}{positionText}: {level.ToString()}: {text}");
        }
        /// <summary>
        /// Writes the specified trace level, message and optional exception.
        /// </summary>
        /// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
        /// <param name="message">The trace message.</param>
        /// <param name="ex">The trace exception. This parameter is optional.</param>
        public void Trace(TraceLevel level, string message, Exception ex)
        {
            string traceMessage = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture) + " " + level.ToString("g") + " " + message;

            if (_traceMessages.Count >= 1000)
                _traceMessages.Dequeue();

            _traceMessages.Enqueue(traceMessage);
        }
示例#21
0
 /// <summary>
 /// Creates an entry with the given message text and application-defined event identifier to the event log list.
 /// </summary>
 /// <param name="title">The title.</param>
 /// <param name="message">The string to write to the event log.</param>
 /// <param name="level">Specifies what messages to output for the.</param>
 /// <param name="source">The source denominator of the message.</param>
 public ActivityLogCT(string title, string message, TraceLevel level, string source)
     : this()
 {
     Title = title;
     Body  = message;
     this.ActivityPriority = level.ToString();
     this.ActivitySource   = source;
     this.Expires          = DateTime.Now + new TimeSpan(2, 0, 0, 0);
 }
                public void LogFunctionTraceEvent(TraceLevel level, string subscriptionId, string appName, string functionName, string eventName, string source, string details, string summary, Exception exception = null)
                {
                    var    elements = new string[] { level.ToString(), subscriptionId, appName, functionName, eventName, source, summary, details };
                    string evt      = string.Join(" ", elements.Where(p => !string.IsNullOrEmpty(p)));

                    lock (_syncLock)
                    {
                        Events.Add(evt);
                    }
                }
示例#23
0
        public TraceLevelObject(TraceLevel level)
        {
            TLevel = level;
            Name   = level.ToString();

            if ((Properties.Settings.Default.ColoredLevels & (int)level) != 0)
            {
                RowColors = ColorUtil.TraceLevelPalette[level];
            }
        }
示例#24
0
            public void WriteLine(string message, TraceLevel lvl = TraceLevel.TRACE)
            {
                var timestamp = UseTimeStamp ? DateTime.Now.ToString("u") + " " : "";

                var lvlStr = lvl == TraceLevel.NONE ? "" : $"[{lvl.ToString()}]:";

                lock (TraceStream)
                {
                    TraceStream.WriteLine($"{timestamp}{lvlStr}{message}");
                }
            }
        public void Format_Verbose_Builds_Trace_With_All_TraceRecord_Properties(TraceLevel level)
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage
            {
                RequestUri = new Uri("http://localhost"),
                Method     = HttpMethod.Get
            };

            InvalidOperationException exception;

            try
            {
                // Want the full stack trace in the payload
                throw new InvalidOperationException("TestException");
            }
            catch (InvalidOperationException ex)
            {
                exception = ex;
            }

            TraceRecord traceRecord = new TraceRecord(request, "TestCategory", level)
            {
                Message   = "TestMessage",
                Operation = "TestOperation",
                Operator  = "TestOperator",
                Status    = HttpStatusCode.Accepted,
                Exception = exception
            };

            // Act
            string formattedTrace = new SystemDiagnosticsTraceWriter()
            {
                IsVerbose = true
            }.Format(
                traceRecord
                );

            // Assert
            AssertContainsExactly(
                formattedTrace,
                new Dictionary <string, string>
            {
                { "Level", level.ToString() },
                { "Kind", TraceKind.Trace.ToString() },
                { "Category", "'TestCategory'" },
                { "Id", request.GetCorrelationId().ToString() },
                { "Message", "'TestMessage'" },
                { "Operation", "TestOperator.TestOperation" },
                { "Status", "202 (Accepted)" },
                { "Exception", exception.ToString() },
            }
                );
        }
示例#26
0
        private static void TraceLine(TraceLevel level, string format, object[] args)
        {
            if ((args == null) || (args.Length == 0))
            {
                format = format.Replace("{", "{{");
                format = format.Replace("}", "}}");
            }

            string message = /*DateTime.Now.ToString("HH:mm:ss") + " : " +*/ string.Format(format, args);

            Trace.WriteLineIf(DoTrace(level), message, level.ToString());
        }
示例#27
0
文件: Log.cs 项目: bisato/bitdiffer
		private static void TraceLine(TraceLevel level, string format, object[] args)
		{
			if ((args == null) || (args.Length == 0))
			{
				format = format.Replace("{", "{{");
				format = format.Replace("}", "}}");
			}

			string message = /*DateTime.Now.ToString("HH:mm:ss") + " : " +*/ string.Format(format, args);

			Trace.WriteLineIf(DoTrace(level), message, level.ToString());
		}
示例#28
0
        public void Log(string message, TraceLevel level)
        {
            Log log = new Log
            {
                Message = message,
                Date    = DateTime.Now,
                Level   = level.ToString()
            };

            Context.Logs.Add(log);
            Context.SaveChanges();
        }
示例#29
0
        private void UpdateLogLevelUI(TraceLevel level)
        {
            // set menu item
            foreach (var pair in this.logLevelMenuItemGroup)
            {
                pair.Item1.IsChecked = (pair.Item2 == level);
            }

            this.levelValueLabel.Content = level.ToString();

            return;
        }
示例#30
0
        public override void OnTcTrace(TraceLevel level, string text)
        {
            string msg = TcTrace.GetTraceTimeString() + " - " + level.ToString().Substring(0, 1) + " : " + text;

            foreach (object o in controls)
            {
                if (o is WpfListerControl)
                {
                    ((WpfListerControl)o).AddLogMessage(msg);
                }
            }
        }
示例#31
0
 public void TracerLog(TraceLevel level, object obj)
 {
     using (DatabaseContext context = new DatabaseContext())
     {
         context.Log.Add(new DatabaseLog
         {
             Message    = (string)obj,
             TraceLevel = level.ToString(),
             Timestamp  = DateTime.Now
         });
     }
 }
    private static void InternalWrite(TraceLevel level, string format, params object[] args)
    {
        try
        {
            if (_init == 0)
            {
                if (0 == System.Threading.Interlocked.Exchange(ref _init, 1))
                {
                    Open();
                }
            }

            int depth = 2;
            if (args.Length > 0)
            {
                format = String.Format(format, args);
            }

            if (level <= _consoleLogLevel)
            {
                Console_LogWrite(level, format);
            }

            StackFrame frame;
            System.Reflection.MethodBase method;

            do
            {
                frame  = new StackFrame(depth++);
                method = frame.GetMethod();
            }while (method.ReflectedType.FullName.StartsWith("System.", StringComparison.OrdinalIgnoreCase) ||
                    method.ReflectedType.GetCustomAttributes(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute), true).Length > 0);

            string methodName, callingType;
            methodName  = String.Format("{0}", method);
            callingType = String.Format("{0}", method.ReflectedType);

            string full = String.Format("{0:D2}{1,8} - {2}   at {3}",
                                        System.Threading.Thread.CurrentThread.ManagedThreadId,
                                        level == TraceLevel.Off ? "None" : level.ToString(),
                                        format, methodName);

            Trace.WriteLine(full, callingType);

            if (LogWrite != null)
            {
                LogWrite(method, level, format);
            }
        }
        catch (Exception e)
        { Trace.WriteLine(e.ToString(), "CSharpTest.Net.QuickLog.Write()"); }
    }
示例#33
0
        private static void Log(string message, TraceLevel level)
        {
            //TODO: Need to implement for real. Right now we just Debug Trace
            if ((Level & level) != 0)
            {
                System.Diagnostics.Debug.WriteLine($"{level.ToString().ToUpper()}: {message}");
            }

            if (traceListener != null)
            {
                traceListener(message);
            }
        }
        /// <summary>
        /// Writes the specified trace level, message and optional exception.
        /// </summary>
        /// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
        /// <param name="message">The trace message.</param>
        /// <param name="ex">The trace exception. This parameter is optional.</param>
        public void Trace(TraceLevel level, string message, Exception ex)
        {
            if (_traceMessages.Count >= 1000)
                _traceMessages.Dequeue();

            StringBuilder sb = new StringBuilder();
            sb.Append(DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture));
            sb.Append(" ");
            sb.Append(level.ToString("g"));
            sb.Append(" ");
            sb.Append(message);

            _traceMessages.Enqueue(sb.ToString());
        }
示例#35
0
        public static void Initialize(string logName, TraceLevel level)
        {
			if (!initialized)
			{
				Level = level;

				if (writer == null && Level > TraceLevel.Off)
				{
					writer = new InternalTraceWriter(logName);
					writer.WriteLine("InternalTrace: Initializing at level " + Level.ToString());
				}

				initialized = true;
			}
        }
示例#36
0
        public static void Log(TraceLevel level, string message, string category, Exception ex)
        {
            Writer.WriteLine("{0} {1,-5} [{2,2}] {3}: {4}",
                DateTime.Now.ToString(TIME_FMT),
                level == TraceLevel.Verbose ? "Debug" : level.ToString(),
#if NET_2_0
                System.Threading.Thread.CurrentThread.ManagedThreadId,
#else
                AppDomain.GetCurrentThreadId(),
#endif
                category,
                message);

            if (ex != null)
                Writer.WriteLine(ex.ToString());
        }
 // Token: 0x060002C0 RID: 704
 // RVA: 0x0002F2C8 File Offset: 0x0002D4C8
 public void Trace(TraceLevel level, string message, Exception ex)
 {
     string item = string.Concat(new string[]
     {
         DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture),
         " ",
         level.ToString("g"),
         " ",
         message
     });
     if (this._traceMessages.Count >= 1000)
     {
         this._traceMessages.Dequeue();
     }
     this._traceMessages.Enqueue(item);
 }
        public static IisExpressWrapper Start(string appPath, TraceLevel traceLevel = TraceLevel.none)
        {
            int port =
                CassiniDev.CassiniNetworkUtils.GetAvailablePort(
                    8000,
                    8999,
                    System.Net.IPAddress.Loopback,
                    includeIdlePorts: false);

            if (port == 0)
            {
                throw new ApplicationException("Couldn't get available port for new IISExpress instance.");
            }

            var startInfo = new System.Diagnostics.ProcessStartInfo()
            {
                Arguments = String.Format(@"/path:""{0}"" /systray:true /clr:v4.0 /trace:{1} /port:{2}", appPath, traceLevel.ToString(), port),
                FileName = @"C:\Program Files (x86)\IIS Express\iisexpress.exe",
                WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
                RedirectStandardError = true,
                //RedirectStandardInput = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
            };

            var process = System.Diagnostics.Process.Start(startInfo);

            var iew = new IisExpressWrapper(appPath, port, process);

            process.OutputDataReceived += iew.process_OutputDataReceived;
            process.ErrorDataReceived += iew.process_ErrorDataReceived;

            process.BeginErrorReadLine();
            process.BeginOutputReadLine();

            // Hack: wait a little for IIS Express to start.
            iew._iisStartedEvent.Wait(TimeSpan.FromMilliseconds(2000));

            return iew;
        }
示例#39
0
        public static void writeAudit(string appName, TraceLevel traceLevel, string message, string userID)
        {
            if (traceType == TraceType.DB || traceType == TraceType.Both)
            {
                Trace trace = new Trace();
                trace.AppName = appName;
                trace.Message = message;
                trace.TraceType = (short)traceLevel;
                trace.TraceLevel = (short)traceLevel;
                trace.UserID = userID;
                trace.CreateDateTime = DateTime.Now;

                DBLogs.Traces.Add(trace);
                DBLogs.SaveChanges();
            }
            if (traceType == TraceType.File || traceType == TraceType.Both)
            {
                string msg = string.Empty;
                msg = DateTime.Now.ToLongDateString() + " : " + appName + " : " + traceLevel.ToString() + " : " +
                    message + " : " + userID;
                writeFile(msg,WS_LogsFilePath + "\\" + traceFileName);
            }
        }
示例#40
0
 private LogLevel GetLogLevel(TraceLevel level)
 {
     // translates webapi log level to nlog log level
     return LogLevel.FromString(level.ToString());
 }
示例#41
0
        private string GetSectionPrefix(TraceLevel traceLevel)
        {
            const int fixedLengthTraceLevel = 7;
            int postFixLength = fixedLengthTraceLevel - traceLevel.ToString().Length;
            var strTrcLvl = traceLevel.ToString().PadRight(postFixLength);

            var prefix = string.Format("[{0}] ", strTrcLvl);
            for (var i = 0; i < _indentLevel; i++)
            {
                prefix += LEVEL_INDICATOR;
            }
            return prefix;
        }
示例#42
0
        private void writeToTextFile(TraceLevel messageLevel, string message)
        {
            this.pLogFileMutex.Lock();
            StreamWriter writer = null;

            try
            {
                writer = new StreamWriter(this.pLogFilePath + this.pLogFileName + "_" + DateTime.Today.ToString("yyyy-MM-dd"), true);
                writer.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "," + Csv.Escape(this.pLoggingSystemName) + ",'" + Csv.Escape(messageLevel.ToString()) + "'," + Csv.Escape(message));
                writer.Close();
                this.pLogFileMutex.Unlock();
            }
            catch (Exception)
            {
                if (writer != null)
                {
                    writer.Close();
                }

                this.pLogFileMutex.Unlock();
            }
        }
 public string GetWithNullableEnumParameter(TraceLevel? level)
 {
     return level.ToString();
 }
        public void SetParameterTraceLevel(TraceLevel traceLevel)
        {
            var configFileParameters = new ConfigFileParameters { TraceLevel = traceLevel };
            var pathParameters = new PathParameters { TraceLevel = traceLevel };

            var expected = " /trace:" + traceLevel.ToString().ToLower();

            configFileParameters.ToString().Should().Be(expected);
            pathParameters.ToString().Should().Be(expected);
        }
示例#45
0
 private static void Log(TraceLevel level, string message)
 {
     string.Format("{0}:{1}:{2}: {3}",
         (object) (level != TraceLevel.Off ? level.ToString().PadRight(7) : "Always".PadRight(7)),
         (object) DateTime.UtcNow.ToString("yyyyMMdd.HHmmss"),
         (object) ("(" + DateTime.Now.ToString("yyyyMMdd.HHmmss:fffff ") + ")"), (object) message);
 }
    private static void InternalWrite(TraceLevel level, string format, params object[] args)
    {
        try
        {
            if (_init == 0)
            {
                if (0 == System.Threading.Interlocked.Exchange(ref _init, 1))
                { Open(); }
            }

            int depth = 2;
            if (args.Length > 0)
                format = String.Format(format, args);

            if (level <= _consoleLogLevel)
                Console_LogWrite(level, format);

            StackFrame frame;
            System.Reflection.MethodBase method;

            do
            {
                frame = new StackFrame(depth++);
                method = frame.GetMethod();
            }
            while (method.ReflectedType.FullName.StartsWith("System.", StringComparison.OrdinalIgnoreCase) ||
                method.ReflectedType.GetCustomAttributes(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute), true).Length > 0);

            string methodName, callingType;
            methodName = String.Format("{0}", method);
            callingType = String.Format("{0}", method.ReflectedType);

            string full = String.Format("{0:D2}{1,8} - {2}   at {3}",
                System.Threading.Thread.CurrentThread.ManagedThreadId,
                level == TraceLevel.Off ? "None" : level.ToString(),
                format, methodName);

            Trace.WriteLine(full, callingType);

            if (LogWrite != null)
                LogWrite(method, level, format);
        }
        catch (Exception e)
        { Trace.WriteLine(e.ToString(), "CSharpTest.Net.QuickLog.Write()"); }
    }
        public void Trace_Verbose_Writes_Correct_Message_To_TraceListeners_With_All_Fields_Set(TraceLevel level)
        {
            // Arrange
            SystemDiagnosticsTraceWriter writer = CreateTraceWriter();
            writer.MinimumLevel = level;
            writer.IsVerbose = true;

            HttpRequestMessage request = new HttpRequestMessage
            {
                RequestUri = new Uri("http://localhost"),
                Method = HttpMethod.Get
            };

            InvalidOperationException exception = new InvalidOperationException("TestException");

            // Act
            writer.Trace(request, "TestCategory", level, (tr) =>
            {
                tr.Message = "TestMessage";
                tr.Operation = "TestOperation";
                tr.Operator = "TestOperator";
                tr.Status = HttpStatusCode.Accepted;
                tr.Exception = exception;
            });

            // Assert
            string expected = String.Format("Level={0}, Kind=Trace, Category='TestCategory', Id={1}, Message='TestMessage', Operation=TestOperator.TestOperation, Status=202 (Accepted), Exception={2}",
                                                level.ToString(),
                                                request.GetCorrelationId().ToString(),
                                                exception.ToString());

            string actual = ((TestTraceListener)writer.TraceSource.Listeners[0]).Messages[0].Trim();
            string timePrefix = "] ";
            actual = actual.Substring(actual.IndexOf(timePrefix) + timePrefix.Length);
            Assert.Equal(expected, actual);
        }
        public void Format_Verbose_Builds_Trace_With_All_TraceRecord_Properties(TraceLevel level)
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage
            {
                RequestUri = new Uri("http://localhost"),
                Method = HttpMethod.Get
            };

            InvalidOperationException exception;
            try
            {
                // Want the full stack trace in the payload
                throw new InvalidOperationException("TestException");
            }
            catch (InvalidOperationException ex)
            {
                exception = ex;
            }

            TraceRecord traceRecord = new TraceRecord(request, "TestCategory", level)
            {
                Message = "TestMessage",
                Operation = "TestOperation",
                Operator = "TestOperator",
                Status = HttpStatusCode.Accepted,
                Exception = exception
            };

            // Act
            string formattedTrace = new SystemDiagnosticsTraceWriter() { IsVerbose = true }.Format(traceRecord);

            // Assert
            AssertContainsExactly(formattedTrace,
                                new Dictionary<string, string>
                                    {
                                        { "Level", level.ToString() },
                                        { "Kind", TraceKind.Trace.ToString() },
                                        { "Category", "'TestCategory'"},
                                        { "Id", request.GetCorrelationId().ToString() },
                                        { "Message", "'TestMessage'" },
                                        { "Operation", "TestOperator.TestOperation" },
                                        { "Status", "202 (Accepted)" },
                                        { "Exception", exception.ToString() },
                                    });

        }
示例#49
0
        //private void InitializeConfigFile()
        //{
        //  _appConfigFile = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "nHydrate\\" + _configName));
        //  if (!_appConfigFile.Directory.Exists)
        //    _appConfigFile.Directory.Create();
        //  if (!_appConfigFile.Exists)
        //    _appConfigFile.Create();
        //  _appFileWatcher = new FileSystemWatcher(_appConfigFile.DirectoryName, _appConfigFile.Name);
        //  _appFileWatcher.NotifyFilter = NotifyFilters.LastWrite;
        //  _appFileWatcher.Changed += new FileSystemEventHandler(mAppFileWatcher_Changed);
        //  _appFileWatcher.EnableRaisingEvents = true;
        //}
        #endregion

        #region TraceStatements
        private static void Log(TraceLevel level, string message)
        {
            string traceLevelString;
            if (level == TraceLevel.Off)
            {
                traceLevelString = "Always";
                traceLevelString = traceLevelString.PadRight(7);
            }
            else
            {
                traceLevelString = level.ToString();
                traceLevelString = traceLevelString.PadRight(7);
            }
            var logString = String.Format("{0}:{1}: {2}", traceLevelString, DateTime.UtcNow.ToString("yyyyMMdd.HHmmss"), message);
            Trace.WriteLine(logString);
        }
 public void SettingTraceLevelTo(TraceLevel level)
 {
     var target = new Parameters {Trace = level};
     var expected = " /trace:" + level.ToString().ToLower();
     target.ToString().Should().Be(expected);
 }
示例#51
0
        // ----------------------------------------------------------------------
        private void Log( TraceLevel logLevel, object message, Exception exception )
        {
            if ( !IsSupportedException( exception ) )
            {
                return;
            }

            if ( level.Level >= logLevel )
            {
                StringBuilder buf = new StringBuilder( name );
                buf.Append( ": " );
                switch ( logLevel )
                {
                    case TraceLevel.Off:
                        buf.Append( "Fatal" );
                        break;
                    case TraceLevel.Verbose:
                        buf.Append( "Debug" );
                        break;
                    default:
                        buf.Append( logLevel.ToString() );
                        break;
                }
                buf.Append( ": " );
                if ( message != null )
                {
                    buf.Append( message );
                }
                if ( exception != null )
                {
                    buf.Append( ": " );
                    buf.Append( exception.ToString() );
                }
                switch ( logLevel )
                {
                    case TraceLevel.Off: // used by 'fatal'
                    case TraceLevel.Error:
                        Trace.TraceError( buf.ToString() );
                        break;
                    case TraceLevel.Warning:
                        Trace.TraceWarning( buf.ToString() );
                        break;
                    case TraceLevel.Info:
                        goto default;
                    case TraceLevel.Verbose:
                        goto default;
                    default:
                        Trace.TraceInformation( buf.ToString() );
                        break;
                }
            }
        }
示例#52
0
 public static void TurnTraceSwitchOn(TraceLevel traceLevel = TraceLevel.Info)
 {
     TraceSwitch = new TraceSwitch("DataConnection", "DataConnection trace switch", traceLevel.ToString());
 }
示例#53
0
 static void log(TraceLevel level, string message)
 {
     bool log = false;
     switch (level)
     {
         case TraceLevel.Info:
             log = TRACE_SWITCH.TraceInfo;
             break;
         case TraceLevel.Error:
             log = TRACE_SWITCH.TraceError;
             break;
         case TraceLevel.Verbose:
             log = TRACE_SWITCH.TraceVerbose;
             break;
         case TraceLevel.Warning:
             log = TRACE_SWITCH.TraceWarning;
             break;
     }
     Trace.WriteLineIf(log, string.Format("{0} {1}: {2}", DateTime.Now.ToString("yyyyMMdd HH:mm:ss.ff"), level.ToString(), message));
 }
示例#54
0
        /// <summary>
        /// Writes a message to the log
        /// </summary>
        /// <param name="message"></param>
        /// <param name="level"></param>
        public void Write(string message, TraceLevel level)
        {
            if (!MayWriteType(level))
                return;

            var caller = "TShock";

            var frame = new StackTrace().GetFrame(2);
            if (frame != null)
            {
                var meth = frame.GetMethod();
                if (meth != null && meth.DeclaringType != null)
                    caller = meth.DeclaringType.Name;
            }

            var logEntry = string.Format("{0} - {1}: {2}: {3}",
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
                    caller, level.ToString().ToUpper(), message);
            try
            {
                _logWriter.WriteLine(logEntry);
                _logWriter.Flush();
            }
            catch (ObjectDisposedException)
            {
                ServerApi.LogWriter.PluginWriteLine(TShock.instance, logEntry, TraceLevel.Error);
                Console.WriteLine("Unable to write to log as log has been disposed.");
                Console.WriteLine("{0} - {1}: {2}: {3}",
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
                    caller, level.ToString().ToUpper(), message);
            }
        }
示例#55
0
 private void writeLog(TraceLevel level, string value)
 {
     if (level <= this.Level && textBox != null)
       {
     textBox.AppendText(DateTime.Now+" "+level.ToString()+": "+value+"\r\n");
     textBox.Refresh();
       }
       if(level <= this.Level && logStream != null)
       {
     byte[] ss = Encoding.ASCII.GetBytes(DateTime.Now+" "+level.ToString()+": "+value+"\r\n");
     logStream.Write(ss, 0, ss.Length);
     logStream.Flush();
       }
       Trace.WriteLineIf(level <= this.Level, DateTime.Now+" "+level.ToString()+": "+value);
 }
示例#56
0
        private static void doWrite(string message, TraceLevel level = TraceLevel.Info)
        {
            string line = "[" + DateTime.Now.ToString() + "]";
            line += "[" + level.ToString() + "]" + "[" + message + "]";
            StackTrace st = new StackTrace();
            if (st.FrameCount < 2)
            {
                line += "[UNKNOWN_PACKAGE::UNKNOWN_METHOD]";
            }
            else
            {
                int verboseStacktraceLength = st.FrameCount;
                string stack = "";
                if (level != TraceLevel.Verbose)
                    verboseStacktraceLength = 3;

                for ( int frameIdx = 2; frameIdx < verboseStacktraceLength; frameIdx++ )
                {
                    stack += "\n";
                    if (frameIdx > 2)
                        stack += "  ";

                    StackFrame sf = st.GetFrame(frameIdx);
                    MethodBase mb = sf.GetMethod();
                    stack += "[" + mb.Module.Name + "::" + mb.DeclaringType.FullName + "::" + mb.Name + "]";
                    if (level == TraceLevel.Error || level == TraceLevel.Verbose)
                        stack += "[" + sf.GetFileName() + "::" + sf.GetFileLineNumber() + "]";
                }
                stack = stack.Substring(1);
                line += stack;
            }
            System.Diagnostics.Trace.WriteLine( line );

            foreach ( TraceCallback fn in _callbacks )
                fn.Invoke( line );
        }