コード例 #1
0
ファイル: LogMessageSyslog.cs プロジェクト: views63/Logbert
        /// <summary>
        /// Gets the value to display within a <see cref="DataGridView"/> at the fiven <paramref name="columnIndex"/>.
        /// </summary>
        /// <param name="columnIndex">The index of the column at the <see cref="DataGridView"/>.</param>
        /// <returns>The value to display at the given <paramref name="columnIndex"/>, or <c>null</c> if nothing to display.</returns>
        public override object GetValueForColumn(int columnIndex)
        {
            switch (columnIndex)
            {
            case 1:
                return(mIndex);

            case 2:
                return(mSeverity.ToString());

            case 3:
                return(mLocalTimestamp.ToString(Settings.Default.TimestampFormat));

            case 4:
                return(mTimestamp.Add(mTimeShiftOffset).ToString(
                           Settings.Default.TimestampFormat
                           , CultureInfo.InvariantCulture));

            case 5:
                return(mFacility.ToString());

            case 6:
                return(mLogger);

            case 7:
                return(mMessage);
            }

            return(null);
        }
コード例 #2
0
 private void WriteToStdErr(Severity severity, string message, params object[] paramList)
 {
     try
     {
         lock (ConsoleLockObject)
         {
             Console.ForegroundColor = GetSeverityForegroundColor(severity);
             if (paramList.Length == 0)
             {
                 Console.Error.WriteLine($"{GetTimestamp()} {severity.ToString().ToUpperInvariant()}: {message}");
             }
             else
             {
                 Console.Error.WriteLine($"{GetTimestamp()} {severity.ToString().ToUpperInvariant()}: {message}\n{{0}}", paramList);
             }
             Console.ForegroundColor = _consoleForegroundColor;
         }
     }
     catch (Exception ex)
     {
         lock (ConsoleLockObject)
         {
             Console.ForegroundColor = _consoleForegroundColor;
         }
         Console.WriteLine($"Logging failed: {ex.Message}");
     }
 }
コード例 #3
0
        private void buildLogEntry(Severity severity, string message, out string logEntry, out string shortLogEntry)
        {
            logEntry      = "";
            shortLogEntry = "";

            if (_addTimeStamp && _addSeverityLevel)
            {
                logEntry      = String.Format("{0:MM/dd/yyyy hh:mm:ss tt} {1,-8}: {2}", DateTime.Now, severity.ToString("F"), message);
                shortLogEntry = String.Format("{0,-8}: {1}", severity.ToString("F"), message);
            }
            else
            if (!_addTimeStamp && _addSeverityLevel)
            {
                logEntry      = String.Format("{{0,-8}: {1}", severity.ToString("F"), message);
                shortLogEntry = logEntry;
            }
            else
            if (_addTimeStamp && !_addSeverityLevel)
            {
                logEntry      = String.Format("{0:MM/dd/yyyy hh:mm:ss tt}: {1}", DateTime.Now, message);
                shortLogEntry = message;
            }
            else
            {
                logEntry      = message;
                shortLogEntry = message;
            }
        }
コード例 #4
0
ファイル: ConsoleLog.cs プロジェクト: vijayamazon/ezbob
        protected override void OwnSay(Severity nSeverity, Exception ex, string format, params object[] parameters)
        {
            Console.Write("{0} {1} ", CurrentTime, nSeverity.ToString());

            Console.WriteLine(format, parameters);

            Console.Write("{0} {1} ", CurrentTime, nSeverity.ToString());
            Console.WriteLine(ExceptionToString(ex));
        } // OwnSay
コード例 #5
0
 public IEvent GetEvent(Exception ex, IUser user, IDevice device, object metaData)
 {
     return(new Event(ex)
     {
         App = App,
         Device = device,
         User = user,
         Severity = _severity.ToString(),
         MetaData = metaData,
     });
 }
コード例 #6
0
        public void AddSeverityRules(Severity severity, Action action)
        {
            RuleSet(severity.ToString(), action);

            foreach (PropertyRule rule in this)
            {
                if (rule.RuleSets.Any(x => string.Equals(x, severity.ToString())))
                {
                    rule.CurrentValidator.Options.Severity = severity;
                }
            }
        }
コード例 #7
0
ファイル: FileLog.cs プロジェクト: vijayamazon/ezbob
        protected override void OwnSay(Severity nSeverity, Exception ex, string format, params object[] parameters)
        {
            lock (m_oLock) {
                m_oLogFile.Write("{0} {1} ", CurrentTime, nSeverity.ToString());

                m_oLogFile.WriteLine(format, parameters);

                m_oLogFile.Flush();

                m_oLogFile.Write("{0} {1} ", CurrentTime, nSeverity.ToString());
                m_oLogFile.WriteLine(ExceptionToString(ex));

                m_oLogFile.Flush();
            }     // lock
        }         // OwnSay
コード例 #8
0
ファイル: IMessageSink.cs プロジェクト: bel-uwa/Loyc
        public static string FormatMessage(Severity type, object context, string format, params object[] args)
        {
            string loc       = LocationString(context);
            string formatted = Localize.From(format, args);

            if (string.IsNullOrEmpty(loc))
            {
                return(Localize.From(type.ToString()) + ": " + formatted);
            }
            else
            {
                return(loc + ": " +
                       Localize.From(type.ToString()) + ": " + formatted);
            }
        }
コード例 #9
0
        public void Write(TextWriter wtr)
        {
            wtr.Write(Timestamp.ToString("s", Cult.InvariantCulture));
            wtr.Write(" - ");
            wtr.Write(Severity.ToString());
            wtr.Write(" - ");
            wtr.WriteLine(Message);

            Exception ex     = Exception;
            Int32     indent = 1;

            while (ex != null)
            {
                String indentString = "".PadRight(indent, '\t');

                wtr.WriteLine(indentString + ex.GetType().Name);
                wtr.WriteLine(indentString + ex.Message);

                String[] stackTrace = ex.StackTrace.Replace("\r\n", "\n").Split('\n');

                foreach (String call in stackTrace)
                {
                    // indent the stack trace at (indent + 1)
                    wtr.Write(indentString + '\t');
                    wtr.WriteLine(call);
                }

                ex = ex.InnerException;

                indent++;
            }
        }
コード例 #10
0
        private void MsgSeverityOk(Severity severity)
        {
            var msg = CreateMessage(severity);

            Assert.Equal(severity, msg.Severity);
            Assert.Equal(severity.ToString(), msg.Get(MessageTokens.Severity));
        }
コード例 #11
0
        public string GetValidationMessagesAsJson()
        {
            var rawMessage = new JsonComparisonMessage
            {
                id      = Id.ToString(),
                code    = Code.ToString(),
                message = Message,
                type    = Severity.ToString(),
                docUrl  = DocUrl.ToString(),
                mode    = Mode.ToString(),
                old     = new JsonLocation
                {
                    @ref     = OldJsonRef,
                    path     = OldJson()?.Path,
                    location = OldLocation(),
                },
                @new = new JsonLocation
                {
                    @ref     = NewJsonRef,
                    path     = NewJson()?.Path,
                    location = NewLocation(),
                }
            };

            return(JsonConvert.SerializeObject(
                       rawMessage,
                       Formatting.Indented,
                       new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            }
                       ));
        }
コード例 #12
0
            internal void ToStringBuilder(StringBuilder buffer)
            {
                if (Severity != null)
                {
                    buffer.Append("[");
                    buffer.Append(Severity.ToString().ToUpper());
                    buffer.Append("] ");
                }

                buffer.Append(Details?.Text ?? "(no details)");

                if (Diagnostics != null)
                {
                    buffer.Append("(further diagnostics: ");
                    buffer.Append(Diagnostics);
                    buffer.Append(")");
                }

                if (Location.Any())
                {
                    buffer.Append(" (at ");
                    buffer.Append(String.Join(" via ", Location));
                    buffer.Append(")");
                }
            }
コード例 #13
0
 public static void Log(string message, Severity severity = Severity.Info)
 {
     if ((int)CurrentLevel >= (int)severity)
     {
         Console.WriteLine($"[{severity.ToString()}] {message}");
     }
 }
コード例 #14
0
ファイル: ZeroLog.cs プロジェクト: dzhendong/Zero
 /// <summary>
 /// Log a message.  The current logging level is used to determine
 ///		if the message is appended to the configured appender
 ///		or if it is ignored.
 /// </summary>
 /// <param name="category">The category to which this log statement belongs.</param>
 /// <param name="s">The severity of the logging message.</param>
 /// <param name="errorMsg">A concise description of the problem encountered.</param>
 /// <param name="args">Variable values that are to be captured with the logging statement.</param>
 public static void Log(Severity s, string errorMsg, params object[] args)
 {
     if (args != null && args.Length > 0)
         LogMessage(s, Format(s.ToString() + ": " + errorMsg, args), null);
     else
         LogMessage(s, errorMsg, null);
 }
コード例 #15
0
ファイル: Cut.cs プロジェクト: alexrodwilson/TitleBoutClone
 public Cut(CutLocation location, Severity severity, Action <Fighter> consequence)
 {
     Location    = location;
     Extent      = severity;
     Consequence = consequence;
     Description = $"A {Extent.ToString().ToLower()} cut {getLocationDescription(Location)}.";
 }
コード例 #16
0
        //public JobLogger(IConfig config, int skipFrames)
        //{
        //    _pageName = config.SessionContext.PageName;
        //    _aspSessionId = config.SessionContext.AspSessionId;
        //    _sessionId = config.SessionContext.SessionId;
        //    _clientIp = config.SessionContext.ClientIp;
        //    _syslog = GetLogger(config, skipFrames);
        //}
        protected override void WriteOutput(string message, Severity severity, LogTo logTo)
        {
            if (logTo.HasFlag(LogTo.File))
            {
                _fileHandler.WriteMessage(message, severity.ToString());
            }
            if (logTo.HasFlag(LogTo.DataBase))
            {
                _logDataAccess.InsertMessage(message, (int) severity);
            }
            if (logTo.HasFlag(LogTo.Console))
            {
                //TODO:implements console
                switch(severity)
                {
                    case Severity.Message:
                        Console.ForegroundColor = ConsoleColor.White;
                        break;
                    case Severity.Warning:
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        break;
                    case Severity.Error:
                        Console.ForegroundColor = ConsoleColor.Red;
                        break;
                    default:
                        Console.ForegroundColor = ConsoleColor.White;
                        break;
                }

                Console.WriteLine("{0} {1}", DateTime.Now.ToShortDateString(), message);
            }
        }
コード例 #17
0
ファイル: BasicSinks.cs プロジェクト: qwertie/ecsharp
		protected virtual ConsoleColor PickColor(Severity level, out string levelText)
		{
			bool isDetail = ((int)level & 1) != 0;
			bool implicitLevel = level < PrintSeverityAt || isDetail;
			ConsoleColor color;

			if (level >= Severity.CriticalDetail)
				color = isDetail ? ConsoleColor.DarkMagenta : ConsoleColor.Magenta;
			else if (level >= Severity.ErrorDetail)
				color = isDetail ? ConsoleColor.DarkRed : ConsoleColor.Red;
			else if (level >= Severity.WarningDetail)
				color = isDetail ? ConsoleColor.DarkYellow : ConsoleColor.Yellow;
			else if (level >= Severity.NoteDetail)
				color = isDetail ? ConsoleColor.Gray : ConsoleColor.White;
			else if (level >= Severity.DebugDetail)
				color = isDetail ? ConsoleColor.DarkCyan : ConsoleColor.Cyan;
			else if (level >= Severity.VerboseDetail)
				color = isDetail ? ConsoleColor.DarkCyan : ConsoleColor.DarkCyan;
			else
				color = Console.ForegroundColor;

			levelText = implicitLevel ? null : level.ToString().Localized();
			_lastColor = color;
			return color;
		}
コード例 #18
0
ファイル: SeverityEx.cs プロジェクト: AndriyMik/SimplyFast
        public static string ToStr(this Severity severity, string format = null)
        {
            if (format == null)
            {
                return(severity.ToStrN());
            }
            switch (format)
            {
            case "u":
            case "U":
                return(severity.ToStrU());

            case "l":
            case "L":
                return(severity.ToStrL());

            case "G":
            case "g":
            case "":
            case "F":
            case "f":
                return(severity.ToStrN());

            default:
                return(severity.ToString(format));
            }
        }
コード例 #19
0
        /// <nodoc />
        public string RenderColumn(ColumnKind col, DateTime dateTime, int threadId, Severity severity, string message)
        {
            if (_constColumns.TryGetValue(col, out var constColumnValue))
            {
                return(constColumnValue);
            }

            switch (col)
            {
            case ColumnKind.PreciseTimeStamp:
                return(FormatTimeStamp(dateTime.ToUniversalTime()));

            case ColumnKind.ThreadId:
                return(threadId.ToString());

            case ColumnKind.ProcessId:
                return(System.Diagnostics.Process.GetCurrentProcess().Id.ToString());

            case ColumnKind.LogLevel:
                return(((int)severity).ToString());

            case ColumnKind.LogLevelFriendly:
                return(severity.ToString());

            case ColumnKind.Message:
                return(message);

            default:
                throw Contract.AssertFailure("Unknown column type: " + col);
            }
        }
コード例 #20
0
 public static void Print(Severity severity, string message)
 {
     if (severity > logLevel)
     {
         Console.WriteLine("[" + System.DateTime.Now + "] [" + severity.ToString() + "] " + message);
     }
 }
コード例 #21
0
        private static string FormatLogMessage_Impl(
            DateTime timestamp,
            Severity severity,
            LoggerType loggerType,
            string caller,
            string message,
            IPEndPoint myIPEndPoint,
            Exception exception,
            int errorCode,
            bool includeStackTrace)
        {
            if (severity == Severity.Error)
                message = "!!!!!!!!!! " + message;

            string ip = myIPEndPoint == null ? String.Empty : myIPEndPoint.ToString();
            if (loggerType.Equals(LoggerType.Grain))
            {
                // Grain identifies itself, so I don't want an additional long string in the prefix.
                // This is just a temporal solution to ease the dev. process, can remove later.
                ip = String.Empty;
            }
            string exc = includeStackTrace ? LogFormatter.PrintException(exception) : LogFormatter.PrintExceptionWithoutStackTrace(exception);
            string msg = String.Format("[{0} {1,5}\t{2}\t{3}\t{4}\t{5}]\t{6}\t{7}",
                LogFormatter.PrintTime(timestamp),            //0
                Thread.CurrentThread.ManagedThreadId,   //1
                severity.ToString(),  //2
                errorCode,                              //3
                caller,                                 //4
                ip,                                     //5
                message,                                //6
                exc);      //7

            return msg;
        }
コード例 #22
0
ファイル: LempDemoPanel.cs プロジェクト: sizzles/ecsharp
        void WriteMessageCore(Severity severity, object ctx, string fmt, params object[] args)
        {
            string msg = fmt;

            try {
                msg = Localize.Localized(fmt, args);
            } catch { }

            var pos = GetSourcePos(ctx);

            if (pos == null)
            {
                msg = MessageSink.ContextToString(ctx) + ": " + msg;
            }

            var lvi = new ListViewItem(new string[] {
                pos != null ? pos.Line.ToString() : "",
                pos != null ? pos.PosInLine.ToString() : "",
                severity.ToString(), msg
            });

            lvi.BackColor = severity >= Severity.Error ? Color.Pink :
                            severity >= Severity.Warning ? Color.LightYellow :
                            messageList.BackColor;
            messageList.Items.Add(lvi);
        }
コード例 #23
0
        /// <summary>The method to call during logging to format the log info into a string, which is orleans legacy logging style</summary>
        /// <param name="timestamp">Timestamp of the log message.</param>
        /// <param name="severity">The severity of the message being traced.</param>
        /// <param name="loggerType">The type of logger the message is being traced through.</param>
        /// <param name="caller">The name of the logger tracing the message.</param>
        /// <param name="myIPEndPoint">The <see cref="IPEndPoint"/> of the Orleans client/server if known. May be null.</param>
        /// <param name="message">The message to log.</param>
        /// <param name="exception">The exception to log. May be null.</param>
        /// <param name="errorCode">Numeric event code for this log entry. May be zero, meaning 'Unspecified'.</param>
        /// <param name="includeStackTrace">determine include stack trace or not</param>
        /// <returns></returns>
        public static string FormatLogMessageToLegacyStyle(
            DateTime timestamp,
            Severity severity,
            LoggerType loggerType,
            string caller,
            string message,
            IPEndPoint myIPEndPoint,
            Exception exception,
            int errorCode,
            bool includeStackTrace)
        {
            if (severity == Severity.Error)
            {
                message = "!!!!!!!!!! " + message;
            }

            string ip  = myIPEndPoint == null ? String.Empty : myIPEndPoint.ToString();
            string exc = includeStackTrace ? LogFormatter.PrintException(exception) : LogFormatter.PrintExceptionWithoutStackTrace(exception);
            string msg = String.Format("[{0} {1,5}\t{2}\t{3}\t{4}\t{5}]\t{6}\t{7}",
                                       LogFormatter.PrintDate(timestamp),    //0
                                       Thread.CurrentThread.ManagedThreadId, //1
                                       severity.ToString(),                  //2
                                       errorCode,                            //3
                                       caller,                               //4
                                       ip,                                   //5
                                       message,                              //6
                                       exc);                                 //7

            return(msg);
        }
コード例 #24
0
        public override string ToString()
        {
#pragma warning disable IDE0071 // Simplify interpolation
            return($"[{Severity.ToString()}] {GetType().Name} {DisplayInfo}");

#pragma warning restore IDE0071 // Simplify interpolation
        }
コード例 #25
0
        public void Log(Severity severity, string itemId, string message, string detail = null)
        {
            if (itemId == null)
            {
                itemId = string.Empty;
            }
            if (message == null)
            {
                message = string.Empty;
            }
            if (detail == null)
            {
                detail = string.Empty;
            }
            string msg = String.Join(",", severity.ToString(), CsvEncode(itemId), CsvEncode(message), CsvEncode(detail));

            m_writer.WriteLine(msg);
            if (m_trace != null)
            {
                m_trace.WriteLine(msg);
            }
            ++m_messageCount;
            if (severity > Severity.Message)
            {
                ++m_errorCount;
            }
        }
コード例 #26
0
        private string FormattedSeverity(Severity sev)
        {
            switch (sev)
            {
            case Severity.Debug:
                return("[Debug    ]");

            case Severity.Info:
                return("[Info     ]");

            case Severity.Warn:
                return("[Warn     ]");

            case Severity.Error:
                return("[Error    ]");

            case Severity.Alert:
                return("[Alert    ]");

            case Severity.Critical:
                return("[Critical ]");

            case Severity.Emergency:
                return("[Emergency]");

            default:
                throw new ArgumentException("Unknown severity: " + sev.ToString() + ".");
            }
        }
コード例 #27
0
 public string ToText()
 {
     return(string.Format("{0} {1} {2}",
                          DateTime.ToString("yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture).PadRight(20),
                          Severity.ToString().PadRight(8),
                          Text));
 }
コード例 #28
0
        public static void Log(string message, Severity severity = Severity.Debug)
        {
            ConsoleColor oldColor = Console.ForegroundColor;

            switch (severity)
            {
            case Severity.Debug:
                Console.ForegroundColor = ConsoleColor.Cyan;
                break;

            case Severity.Info:
                Console.ForegroundColor = ConsoleColor.White;
                break;

            case Severity.Warning:
                Console.ForegroundColor = ConsoleColor.Yellow;
                break;

            case Severity.Error:
                Console.ForegroundColor = ConsoleColor.Red;
                break;

            case Severity.Fatal:
                Console.ForegroundColor = ConsoleColor.Magenta;
                throw new Exception("A fatal error occured: " + message);
            }

            Console.WriteLine("[" + Name + "] [" + severity.ToString() + "] " + message);
            Console.ForegroundColor = oldColor;
        }
コード例 #29
0
        private void WriteLog(Severity severity, string content, Exception ex = null)
        {
            StringBuilder s = new StringBuilder("                     ");

            s.Insert(0, DateTime.Now.ToLongTimeString() + " :");
            s.Insert(11, severity.ToString());
            s.Insert(19, $": " + content);

            WriteToLog(s);

            if (ex != null)
            {
                s = new StringBuilder("                     ");
                s.Insert(19, "| " + ex.Message);
                WriteToLog(s);

                if (ex.StackTrace != null)
                {
                    string[] trace = ex.StackTrace.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                    foreach (string x in trace)
                    {
                        string m = x.Trim();
                        s = new StringBuilder("                     ");
                        s.Insert(19, "| " + m);
                        WriteToLog(s);
                    }
                }
            }
        }
コード例 #30
0
        public void Log(DateTime date, Severity severity, string message)
        {
            var cnnSB = new SqlConnectionStringBuilder();

            cnnSB.DataSource     = dbParams.ServerName;
            cnnSB.InitialCatalog = dbParams.Database;
            cnnSB.UserID         = dbParams.UserId;
            cnnSB.Password       = dbParams.Password;

            try
            {
                using (var cnn = new SqlConnection(cnnSB.ToString()))
                {
                    cnn.Open();
                    using (var command = new SqlCommand())
                    {
                        command.Connection  = cnn;
                        command.CommandText = "Insert Into Log(creationDate,severity,message)values(@creationDate,@severity,@message)";
                        command.CommandType = System.Data.CommandType.Text;
                        command.Parameters.AddWithValue("@creationDate", date);
                        command.Parameters.AddWithValue("@severity", severity.ToString());
                        command.Parameters.AddWithValue("@message", message);
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                throw;
            }
        }
コード例 #31
0
        public string GetCssClasses()
        {
            var cssClasses = Type.ToString().Clean()
                             + " " + Severity.ToString().Clean()
                             + " " + Status.ToString().Clean();

            return(cssClasses);
        }
コード例 #32
0
 public void WriteDataTo(BinaryWriter writer)
 {
     writer.WriteGuid(BuildId);
     writer.Write(Severity.ToString());
     writer.Write(Code);
     writer.Write(Message);
     Optional.Write(writer, Source, (Action <BinaryWriter, SourceReference>)SourceReference.Write);
 }
コード例 #33
0
        private void WriteLog(Severity severity, string message)
        {
            string[] fields = { "LogId", "Date", "Severity", "Message" };
            object[] values = { Guid.NewGuid().ToString(), DateTime.Now, severity.ToString().Substring(0, 1), message };

            Query q = new Query().Select(fields).From(tableName).Insert(values);

            dx.ExecuteNonQuery(q.GetSql());
        }
コード例 #34
0
ファイル: ExceptionLog.cs プロジェクト: TokleMahesh/XLog
 public ExceptionLog(Exception exception, string source, string method, Severity severity, string title = "")
     : this()
 {
     Type = exception.GetType().Name;
     StackTrace = exception.StackTrace;
     Source = string.IsNullOrEmpty(source) ? exception.Source : source;
     Severity = severity.ToString();
     Message = exception.Message;
     InnerException = exception.InnerException != null ? exception.InnerException.ToString() : string.Empty;
     AdditionalInfo = FormatExceptionData(exception.Data);
     TargetSite = exception.TargetSite == null ? "" : exception.TargetSite.Name;
     Title = string.IsNullOrEmpty(title) ? method : title;
 }
コード例 #35
0
ファイル: Logger.cs プロジェクト: shekar348/1PointOne
 public void logdata(string logfile, string data, bool logtodb, Severity severity)
 {
     if (logtofile)
     {
         System.IO.File.AppendAllText(logfile, Environment.NewLine + "------------------------------------------------------------------------------------------------");
         System.IO.File.AppendAllText(logfile, string.Format("{0}Timestamp: {1}", Environment.NewLine, DateTime.Now));
         System.IO.File.AppendAllText(logfile, string.Format("{0}Message: {1}", Environment.NewLine, data));
         System.IO.File.AppendAllText(logfile, string.Format("{0}Severity: {1}", Environment.NewLine, severity.ToString()));
         System.IO.File.AppendAllText(logfile, Environment.NewLine + "------------------------------------------------------------------------------------------------");
     }
     if (logtodb)
     {
         //insertIntoJobEventLog(data, job, severity);
     }
 }
コード例 #36
0
        public override bool Log(string Message, Severity severity = Severity.Info)
        {
            try
            {
                string LogFileName = Directory.GetCurrentDirectory() + "LogFile.txt";

                File.AppendAllText(LogFileName, string.Format("Priority({0}) > {1}{2}", severity.ToString(), Message, Environment.NewLine));

            /*
            OR

                    StreamWriter SW = null;
                    try
                    {
                        if (!File.Exists(LogFileName))
                            SW = File.CreateText(LogFileName);
                        else
                            SW = File.AppendText(LogFileName);

                        SW.WriteLine(string.Format("Priority({0}) > {1}", PriorityToText(severity), Message));
                        SW.Close();
                    }
                    finally
                    {
                        if (SW != null)
                            SW.Dispose();
                    }
            */
                return true;
            }
            catch
            {
                return false;
                throw new NotImplementedException();
            }
        }
コード例 #37
0
        public override bool Log(string Message, Severity severity)
        {
            try
                {
                    System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("*****@*****.**", "*****@*****.**");
                    message.Subject = string.Format("Error from app. Priority({0})", severity.ToString());
                    message.Body = string.Format("Priority({0}) > {1}", severity.ToString(), Message);

                    //smtp defaultne bere konfiguraci z app.config souboru. jinak ma pretizeny konstruktor
                    //http://tonesdotnetblog.wordpress.com/2008/10/04/how-to-store-smtp-mail-settings-in-the-appconfig-or-webconfig-file/
                    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
                    client.Send(message);
                    return true;
                }
                catch
                {
                    return false;
                }
        }
コード例 #38
0
 public static void Report(Exception ex, Dictionary<string, string> args, Severity type)
 {
     if (Active) {
         if (Logging.DebugOutline) {
             #region Debug Output
             string key = "";
             string value = "";
             if (args != null && args.Keys.Count>0){//args?.Keys.Count > 0) {
                 key = args.Keys.First ();
                 value = args [key];
             }
             Debug.WriteLine (string.Format("[{0}] {1}: {2};\n\rStackTrace:\n\r{3}", type.ToString(), key,value,ex != null ? ex.ToString():""));
             #endregion
         }
     }
 }
コード例 #39
0
ファイル: MshLog.cs プロジェクト: 40a/PowerShell
        /// <summary>
        /// Generate LogContext structure based on executionContext and invocationInfo passed in.
        /// 
        /// LogContext structure is used in log provider interface. 
        /// </summary>
        /// <param name="executionContext"></param>
        /// <param name="invocationInfo"></param>
        /// <param name="severity"></param>
        /// <returns></returns>
        private static LogContext GetLogContext(ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity)
        {
            if (executionContext == null)
                return null;

            LogContext logContext = new LogContext();

            string shellId = executionContext.ShellID;

            logContext.ExecutionContext = executionContext;
            logContext.ShellId = shellId;
            logContext.Severity = severity.ToString();

            if (executionContext.EngineHostInterface != null)
            {
                logContext.HostName = executionContext.EngineHostInterface.Name;
                logContext.HostVersion = executionContext.EngineHostInterface.Version.ToString();
                logContext.HostId = (string)executionContext.EngineHostInterface.InstanceId.ToString();
            }

            logContext.HostApplication = String.Join(" ", Environment.GetCommandLineArgs());

            if (executionContext.CurrentRunspace != null)
            {
                logContext.EngineVersion = executionContext.CurrentRunspace.Version.ToString();
                logContext.RunspaceId = executionContext.CurrentRunspace.InstanceId.ToString();

                Pipeline currentPipeline = ((RunspaceBase)executionContext.CurrentRunspace).GetCurrentlyRunningPipeline();
                if (currentPipeline != null)
                {
                    logContext.PipelineId = currentPipeline.InstanceId.ToString(CultureInfo.CurrentCulture);
                }
            }

            logContext.SequenceNumber = NextSequenceNumber;

            try
            {
                if (executionContext.LogContextCache.User == null)
                {
                    logContext.User = Environment.UserDomainName + "\\" + Environment.UserName;
                    executionContext.LogContextCache.User = logContext.User;
                }
                else
                {
                    logContext.User = executionContext.LogContextCache.User;
                }
            }
            catch (InvalidOperationException)
            {
                logContext.User = Logging.UnknownUserName;
            }

            System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
                    executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
            if (psSenderInfo != null)
            {
                logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name;
            }

            logContext.Time = DateTime.Now.ToString(CultureInfo.CurrentCulture);

            if (invocationInfo == null)
                return logContext;

            logContext.ScriptName = invocationInfo.ScriptName;
            logContext.CommandLine = invocationInfo.Line;

            if (invocationInfo.MyCommand != null)
            {
                logContext.CommandName = invocationInfo.MyCommand.Name;
                logContext.CommandType = invocationInfo.MyCommand.CommandType.ToString();

                switch (invocationInfo.MyCommand.CommandType)
                {
                    case CommandTypes.Application:
                        logContext.CommandPath = ((ApplicationInfo)invocationInfo.MyCommand).Path;
                        break;
                    case CommandTypes.ExternalScript:
                        logContext.CommandPath = ((ExternalScriptInfo)invocationInfo.MyCommand).Path;
                        break;
                }
            }

            return logContext;
        }
コード例 #40
0
ファイル: Logger.cs プロジェクト: CJDevWorks/SavariWala
		public void Log (Severity sev, string msg)
		{
			Console.WriteLine (sev.ToString () + ": " + msg);
		}
コード例 #41
0
 public LogEvent Severity(Severity severity)
 {
     m_Values.Add("severity", severity.ToString().ToLowerInvariant());
     return this;
 }
コード例 #42
0
ファイル: LocalRunspace.cs プロジェクト: nickchal/pash
 internal void LogEngineHealthEvent(Exception exception, Severity severity, int id, Dictionary<string, string> additionalInfo)
 {
     LogContext logContext = new LogContext {
         EngineVersion = this.Version.ToString(),
         HostId = base.Host.InstanceId.ToString(),
         HostName = base.Host.Name,
         HostVersion = base.Host.Version.ToString(),
         RunspaceId = base.InstanceId.ToString(),
         Severity = severity.ToString()
     };
     if (this.RunspaceConfiguration == null)
     {
         logContext.ShellId = Utils.DefaultPowerShellShellID;
     }
     else
     {
         logContext.ShellId = this.RunspaceConfiguration.ShellId;
     }
     MshLog.LogEngineHealthEvent(logContext, id, exception, additionalInfo);
 }
コード例 #43
0
ファイル: BasicSinks.cs プロジェクト: qwertie/ecsharp
		public void WriteCore(Severity type, object context, string text)
		{
			string loc = MessageSink.ContextToString(context);
			if (!string.IsNullOrEmpty(loc))
				text = loc + ": " + text;
			Trace.WriteLine(text, type.ToString());
		}
コード例 #44
0
 /// <summary>
 /// Sets up the source object
 /// </summary>
 /// <param name="parent">The parent of the source</param>
 /// <param name="severity">Source severity</param>
 public Source( Tag parent, Severity severity )
 {
     m_Severity = severity;
     m_Name = severity.ToString( );
     m_FullName = ( parent.IsRootTag ? m_Name : parent.FullName + "." + m_Name );
 }
コード例 #45
0
ファイル: IMessageSink.cs プロジェクト: default0/LoycCore
		public static string FormatMessage(Severity type, object context, string format, params object[] args)
		{
			string loc = LocationString(context);
			string formatted = Localize.From(format, args);
			if (string.IsNullOrEmpty(loc))
				return Localize.From(type.ToString()) + ": " + formatted;
			else
				return loc + ": " + 
				       Localize.From(type.ToString()) + ": " + formatted;
		}
コード例 #46
0
ファイル: MshLog.cs プロジェクト: nickchal/pash
 private static LogContext GetLogContext(System.Management.Automation.ExecutionContext executionContext, InvocationInfo invocationInfo, Severity severity)
 {
     if (executionContext == null)
     {
         return null;
     }
     LogContext context = new LogContext();
     string shellID = executionContext.ShellID;
     context.ExecutionContext = executionContext;
     context.ShellId = shellID;
     context.Severity = severity.ToString();
     if (executionContext.EngineHostInterface != null)
     {
         context.HostName = executionContext.EngineHostInterface.Name;
         context.HostVersion = executionContext.EngineHostInterface.Version.ToString();
         context.HostId = executionContext.EngineHostInterface.InstanceId.ToString();
     }
     if (executionContext.CurrentRunspace != null)
     {
         context.EngineVersion = executionContext.CurrentRunspace.Version.ToString();
         context.RunspaceId = executionContext.CurrentRunspace.InstanceId.ToString();
         Pipeline currentlyRunningPipeline = ((RunspaceBase) executionContext.CurrentRunspace).GetCurrentlyRunningPipeline();
         if (currentlyRunningPipeline != null)
         {
             context.PipelineId = currentlyRunningPipeline.InstanceId.ToString(CultureInfo.CurrentCulture);
         }
     }
     context.SequenceNumber = NextSequenceNumber;
     try
     {
         if (executionContext.LogContextCache.User == null)
         {
             context.User = Environment.UserDomainName + @"\" + Environment.UserName;
             executionContext.LogContextCache.User = context.User;
         }
         else
         {
             context.User = executionContext.LogContextCache.User;
         }
     }
     catch (InvalidOperationException)
     {
         context.User = Logging.UnknownUserName;
     }
     context.Time = DateTime.Now.ToString(CultureInfo.CurrentCulture);
     if (invocationInfo != null)
     {
         context.ScriptName = invocationInfo.ScriptName;
         context.CommandLine = invocationInfo.Line;
         if (invocationInfo.MyCommand == null)
         {
             return context;
         }
         context.CommandName = invocationInfo.MyCommand.Name;
         context.CommandType = invocationInfo.MyCommand.CommandType.ToString();
         CommandTypes commandType = invocationInfo.MyCommand.CommandType;
         if (commandType != CommandTypes.ExternalScript)
         {
             if (commandType == CommandTypes.Application)
             {
                 context.CommandPath = ((ApplicationInfo) invocationInfo.MyCommand).Path;
             }
             return context;
         }
         context.CommandPath = ((ExternalScriptInfo) invocationInfo.MyCommand).Path;
     }
     return context;
 }
コード例 #47
0
 public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
 {
     Errors.AppendLine(string.Format("{0}:{1} - {2} at Line {3}", new object[] { severity.ToString(), errorCode.ToString(), message, span.Start.Line.ToString() }));
 }
コード例 #48
0
        protected virtual void Write(int msg, [NotNull] string text, Severity severity, [NotNull] string fileName, TextSpan textSpan, [NotNull] string details)
        {
            if (IgnoredMessages.Contains(msg))
            {
                return;
            }

            if (!string.IsNullOrEmpty(details))
            {
                text += ": " + details;
            }

            var fileInfo = !string.IsNullOrEmpty(fileName) ? fileName : "scc.cmd";

            var projectDirectory = Configuration.Get(Constants.Configuration.ProjectDirectory);
            if (!string.IsNullOrEmpty(projectDirectory))
            {
                if (fileInfo.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase))
                {
                    fileInfo = fileInfo.Mid(projectDirectory.Length + 1);
                }
            }

            var lineInfo = textSpan.Length == 0 ? $"({textSpan.LineNumber},{textSpan.LinePosition})" : $"({textSpan.LineNumber},{textSpan.LinePosition},{textSpan.LineNumber},{textSpan.LinePosition + textSpan.Length})";

            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.Write($"{fileInfo}{lineInfo}: ");

            switch (severity)
            {
                case Severity.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;
                case Severity.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;
                default:
                    Console.ForegroundColor = ConsoleColor.DarkGray;
                    break;
            }

            Console.Write(severity.ToString().ToLowerInvariant());

            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.Write(" SCC{0}: ", msg.ToString("0000"));

            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine(text);
        }
コード例 #49
0
 /// <summary>
 /// Checks if the report has the severity.
 /// </summary>
 /// <param name="document">The document.</param>
 /// <param name="value">The value.</param>
 /// <returns><c>true</c> if there is a violation with that severity, <c>false</c> otherwise.</returns>
 private static bool CheckReportForSeverity(XmlDocument document, Severity value)
 {
     var nodes = document.SelectNodes("/CodeItRightReport/Violations/Violation[Severity='" + value.ToString() + "']");
     return nodes.Count > 0;
 }
コード例 #50
0
ファイル: ScriptErrorListener.cs プロジェクト: michyer/canape
        public override void ErrorReported(ScriptSource source, string message, SourceSpan span, int errorCode, Severity severity)
        {
            ScriptError arg = new ScriptError(message, severity.ToString(), span.Start.Line, span.Start.Column);

            Errors.Add(arg);
        }
コード例 #51
0
ファイル: LocalConnection.cs プロジェクト: 40a/PowerShell
        /// <summary>
        /// Logs engine health event
        /// </summary>
        internal void LogEngineHealthEvent(Exception exception,
                             Severity severity,
                             int id,
                             Dictionary<String, String> additionalInfo)
        {
            Dbg.Assert(exception != null, "Caller should validate the parameter");

            LogContext logContext = new LogContext();
            logContext.EngineVersion = Version.ToString();
            logContext.HostId = Host.InstanceId.ToString();
            logContext.HostName = Host.Name;
            logContext.HostVersion = Host.Version.ToString();
            logContext.RunspaceId = InstanceId.ToString();
            logContext.Severity = severity.ToString();
            if (this.RunspaceConfiguration == null)
            {
                logContext.ShellId = Utils.DefaultPowerShellShellID;
            }
            else
            {
                logContext.ShellId = this.RunspaceConfiguration.ShellId;
            }
            MshLog.LogEngineHealthEvent(
                logContext,
                id,
                exception,
                additionalInfo);
        }
コード例 #52
0
        /// <summary>
        /// This method displays the message to the console and also writes it to the log file
        /// </summary>
        /// <param name="type">Severity of the message</param>
        /// <param name="name">name of the task/process</param>
        /// <param name="format">format of the message</param>
        /// <param name="args">variable to use with the format</param>
        public static void Out(Severity type, string name, string format, params object[] args)
        {
            switch (type)
            {
                case Severity.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;
                case Severity.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;
                default:
                    if(name == ExecuteSequence.eventString)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                    }
                    break;
            }

            // writes to the console
            Console.WriteLine(System.DateTime.Now + " " + type.ToString() + "\t: " +
                name + "\t: " + format, args);

            Console.ResetColor();

            // writes to the log file
            if (!string.IsNullOrEmpty(logFileName) && logWriter != null)
            {
                XElement element = new XElement(type.ToString(),
                    new XAttribute("Name", name),
                    new XAttribute("Time", System.DateTime.Now.ToString()),
                    new XElement("Detail", String.Format(format, args)));
                logWriter.WriteLine(element.ToString());
            }
        }
コード例 #53
0
ファイル: AppLog.cs プロジェクト: evihalf/metafetch
        public void Log(Severity severity, string message)
        {
            string logMessage = "[" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + "] " + severity.ToString() + ": " + message;

            m_log.AppendLine(logMessage);
            System.Diagnostics.Debug.WriteLine(logMessage);
        }