public async Task <bool> PostAsync(string url, string message, MessageLevel level = MessageLevel.Info) { // Create an HttpClient and send content payload using (var httpClient = HttpClient) { #if __IOS__ || __ANDROID__ || NET45 var content = new FormUrlEncodedContent(new Dictionary <string, string> { { "message", message }, { "level", level.ToString().ToLower() } }); #endif #if NETFX_CORE var content = new HttpFormUrlEncodedContent(new Dictionary <string, string> { { "message", message }, { "level", level.ToString().ToLower() } }); #endif var response = await httpClient.PostAsync(new Uri(url), content); return(response.IsSuccessStatusCode); } }
public IObservable<bool> Post(string url, string message, MessageLevel level = MessageLevel.Info) { // Create an HttpClient and send content payload using (var httpClient = HttpClient) { #if __IOS__ || __ANDROID__ || NET45 var content = new FormUrlEncodedContent(new Dictionary<string, string> { {"message", message}, {"level", level.ToString().ToLower()} }); #endif #if NETFX_CORE var content = new HttpFormUrlEncodedContent(new Dictionary<string, string> { {"message", message}, {"level", level.ToString().ToLower()} }); #endif #if __IOS__ || __ANDROID__ || NET45 return httpClient.PostAsync(new Uri(url), content) .ToObservable() .Select(response => response.IsSuccessStatusCode); #endif #if NETFX_CORE return httpClient.PostAsync(new Uri(url), content) .AsTask() .ToObservable() .Select(response => response.IsSuccessStatusCode); #endif } }
/// <summary> /// Last chance logging if primary logging sink fails. Usually used on application boot strapping. Log file will be located in /// either the file location of Log.LastChangeLogFile or in the default folder of the running application. NOTE: Bypasses /// any configured log provider (log4Net, NLog, TraceLog, etc) and writes directly to text file. Use with extreme care and is /// not configured for high performance. /// </summary> /// <param name="logLevel">Level this message will be logged at</param> /// <param name="message">Text of message</param> /// <param name="args">Arguments to supply to message text (if any)</param> public static void LastChanceLog(MessageLevel logLevel, string message, params object[] args) { string logMessage = ""; try { _lastChanceLock.EnterWriteLock(); if (CoreConfig.Log.IsLastChanceLogEnabled == false) return; // last chance logging not enabled logMessage = TextUtils.StringFormat("{0:yyyy-MM-dd HH:mm:ss.fff} {1} {2}", DateTime.Now, logLevel.ToString().ToUpper(), TextUtils.StringFormat(message, args)); File.AppendAllText(CoreConfig.Log.LastChanceLogFile, logMessage + Environment.NewLine); } catch (Exception ex) { try // write to event log if unable to log to last chance file. This is really the last chance of the last chance! { EventLog.WriteEntry("Application Error", string.Format(logMessage, args), EventLogEntryType.Error); EventLog.WriteEntry("Application Error", string.Format(ex.ToString()), EventLogEntryType.Error); } catch (Exception ex2) //couldn't write log to last chance log file or event viewer so swallow exception { System.Diagnostics.Debug.WriteLine(string.Format("Error in LastChanceLog: {0}{1}{2}", ex2.Message, Environment.NewLine, logMessage)); } } finally { _lastChanceLock.ExitWriteLock(); } }
/// <summary> /// Determines if a particular LogLevel (serverity of a single message) is enabled to be logged /// </summary> /// <param name="level">Message log level to be checked</param> /// <returns>True if level is enabled to be logged or false if message cannot be logged in this instance</returns> /// <exception cref="ArgumentException">Thrown when level doesn't fall within a known set of elements</exception> public bool IsLevelEnabled(MessageLevel level) { switch (level) { case MessageLevel.Debug: return(((_logLevels & LoggerLevels.Debug) == LoggerLevels.Debug) && (OnLogDebugEventHandler != null)); case MessageLevel.Trace: return(((_logLevels & LoggerLevels.Trace) == LoggerLevels.Trace) && (OnLogTraceEventHandler != null)); case MessageLevel.Information: return(((_logLevels & LoggerLevels.Information) == LoggerLevels.Information) && (OnLogInformationEventHandler != null)); case MessageLevel.Warning: return(((_logLevels & LoggerLevels.Warning) == LoggerLevels.Warning) && (OnLogWarningEventHandler != null)); case MessageLevel.Error: return(((_logLevels & LoggerLevels.Error) == LoggerLevels.Error) && (OnLogErrorEventHandler != null)); case MessageLevel.Critical: return(((_logLevels & LoggerLevels.Critical) == LoggerLevels.Critical) && (OnLogCriticalEventHandler != null)); //case LogLevel.Verbose: return IsLevelEnabled(LogLevel.Debug) && IsLevelEnabled(LogLevel.Trace) && IsLevelEnabled(LogLevel.Information); //case LogLevel.Vital: return IsLevelEnabled(LogLevel.Warning) && IsLevelEnabled(LogLevel.Error) && IsLevelEnabled(LogLevel.Critical); //case LogLevel.All: return IsLevelEnabled(LogLevel.Verbose) && IsLevelEnabled(LogLevel.Vital); case MessageLevel.Off: return((level & MessageLevel.Off) == MessageLevel.Off); default: throw new ArgumentException("Unable to identify LogLevel of '{0}'", level.ToString()); } }
/// <summary> /// Print message to console with level at the front and new line at the end. /// </summary> /// <param name="message">The message to print.</param> /// <param name="level">The level of the message.</param> private void _ConsolePrintMessage(string message, MessageLevel level = MessageLevel.Info) { if (level >= _ConsoleDisplayLevel) { _ConsolePrint("[" + DateTime.Now + "] [" + level.ToString() + "] " + message + "\n"); } }
private void WriteConsoleLogLine(DateTime ts, MessageLevel level, string prefix, string positiveOrNegativeMain, string suffix, bool isPositive) { // prefix is always gray // main is red or green // suffix is gray for info, dark gray for debug and cyan for error Console.ForegroundColor = ConsoleColor.DarkGray; Console.Write(ts.ToString("HH:mm:ss")); Console.ResetColor(); switch (level) { case MessageLevel.Debug: Console.ForegroundColor = ConsoleColor.DarkGray; break; case MessageLevel.Info: Console.ForegroundColor = ConsoleColor.DarkCyan; break; case MessageLevel.Error: Console.ForegroundColor = ConsoleColor.Magenta; break; } Console.Write(" "); Console.Write(level.ToString().Substring(0, 1)); Console.Write(":"); Console.ResetColor(); if (prefix != null) { Console.Write(" "); Console.Write(prefix); } if (positiveOrNegativeMain != null) { Console.Write(" "); Console.ForegroundColor = isPositive ? ConsoleColor.Green : ConsoleColor.Red; Console.Write(positiveOrNegativeMain); Console.ResetColor(); } if (suffix != null) { Console.Write(" "); switch (level) { case MessageLevel.Debug: Console.ForegroundColor = ConsoleColor.DarkGray; break; case MessageLevel.Error: Console.ForegroundColor = ConsoleColor.Magenta; break; } Console.Write(suffix); Console.ResetColor(); } Console.WriteLine(); }
private static void ConsoleMessageCallback(IntPtr ud, View caller, MessageSource source, MessageLevel level, string?message, uint lineNumber, uint columnNumber, string?sourceId) { switch (level) { case MessageLevel.Warning: case MessageLevel.Error: { Console.Error.WriteLine($"{level.ToString()} {source}:{lineNumber}:{columnNumber}: {message}"); Console.Error.Flush(); //Debugger.Break(); break; } default: { Console.WriteLine($"{level.ToString()} {source}:{lineNumber}:{columnNumber}: {message}"); break; } } }
public static Message <T> Generate( MessageLevel messageLevel = MessageLevel.Warning, T identifier = null, string message = null) { if (message == null) { message = $"{messageLevel.ToString()} message"; } return(new Message <T>(messageLevel, message, identifier)); }
public async Task<bool> PostAsync(string url, string message, MessageLevel level = MessageLevel.Info) { // Create an HttpClient and send content payload using (var httpClient = HttpClient) { #if __IOS__ || __ANDROID__ || NET45 var content = new FormUrlEncodedContent(new Dictionary<string, string> { {"message", message}, {"level", level.ToString().ToLower()} }); #endif #if NETFX_CORE var content = new HttpFormUrlEncodedContent(new Dictionary<string, string> { {"message", message}, {"level", level.ToString().ToLower()} }); #endif var response = await httpClient.PostAsync(new Uri(url), content); return response.IsSuccessStatusCode; } }
public static void SendDebug(string ClientName, string Text, MessageLevel Level) { switch (Level) { case MessageLevel.Debug: Console.ForegroundColor = ConsoleColor.DarkGreen; break; case MessageLevel.Error: Console.ForegroundColor = ConsoleColor.DarkRed; break; default: Console.ForegroundColor = ConsoleColor.White; break; } Console.WriteLine($"[Time:{DateTime.Now}] [{ClientName}] [{Level.ToString()}]:{Text}"); }
public static void Log(MessageLevel level, string fmt, params object[] args) { if (level <= maxLevel) { string levelString = '[' + level.ToString().Substring(0, 3) + ']'; string msg = string.Format(levelString + fmt, args); if (UseConsole) { Console.WriteLine(msg); } if (UseFile) { Writer.WriteLine(msg); } System.Diagnostics.Debug.WriteLine(msg); } if (UseConsole) { Console.ResetColor(); } }
private static void GenerateOutputMessage(string logtext, MessageLevel prefix, string source) { switch (LoggingLevel >= prefix) { case true: var _sb = new StringBuilder(); var logtimestamp = DateTime.Now.ToString("MM-dd-yyyy hh:mm:ss:sss.fff", CultureInfo.InvariantCulture); _sb.Append(logtimestamp.PadRight(30)); _sb.Append(prefix.ToString().PadRight(30)); _sb.Append(source.PadRight(40)); _sb.Append(GetCurrentMethod(GetCaller()).PadRight(30)); _sb.Append(logtext); lock (_syncObject) { using (StreamWriter sw = new StreamWriter(LogLocation, true)) { sw.WriteLine(_sb.ToString()); } } break; case false: break; } }
public void Log(string senderName, string message, MessageLevel messageLevel) { if (((uint)_logLevel & (uint)messageLevel) != 0) { string logMessageHeader = String.Format( LogMessage.LogHeaderFormat, DateTime.Now.ToString(Constant.LogDateTimeFormat), messageLevel.ToString()); string logMessageBody = String.Format(LogMessage.LogBodyFormat, senderName, message); lock (SyncWrite) { if (_logStream != null) { _logStream.WriteLine(logMessageHeader); _logStream.WriteLine(logMessageBody); _logStream.WriteLine(); } } } }
public void Log(string senderName, string message, MessageLevel messageLevel) { if (_guiLogAction != null) { _guiLogAction(new LogItem(senderName, messageLevel.ToString(), message)); } try { _logger.Log(senderName, message, messageLevel); } catch (Exception ex) { if (_guiLogAction != null) { _guiLogAction(new LogItem("Logger", MessageLevel.Error.ToString(), ex.ToString())); } else { throw ex; } } }
public void AddMessage(MessageLevel level, string msg) { Dispatcher.BeginInvoke(() => { var item = new MessageType() { Level = level.ToString(), Message = msg }; var itemView = new Button() { //Template = this.Resources["LogItemControl"] as ControlTemplate, ContentTemplate = this.Resources["LogItemData"] as DataTemplate, Content = item, Width = Viewer.ViewportWidth - Viewer.ScrollableWidth, }; switch (level) { case MessageLevel.Info: itemView.Background = this.Resources["InfoBrush"] as Brush; break; default: itemView.Background = this.Resources["ErrorBrush"] as Brush; break; } ViewerContent.Children.Add(itemView); //double scrollAmount = Viewer.Height - Viewer.ScrollableHeight; //if (scrollAmount < 0) //{ // Viewer.ScrollToVerticalOffset(scrollAmount); //} }); }
private static string AddPrefix(string Message, MessageLevel Level) { return(DateTime.Now + " (" + Level.ToString() + ") " + Message); }
public static string GetEntry(MessageLevel level, string source, string message) { return(string.Format("{0} - {3} - {1} - {2}", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.fff"), source, message, level.ToString())); }
private void OutputMessage(string message, MessageLevel level) { if (base.InvokeRequired) { JobMessageLevelCallback method = new JobMessageLevelCallback(this.OutputMessage); base.Invoke(method, new object[] { message, level }); } else { if (!message.EndsWith(Environment.NewLine, StringComparison.OrdinalIgnoreCase)) { message = message + Environment.NewLine; } switch (level) { case MessageLevel.Information: case MessageLevel.Warning: case MessageLevel.Error: this.txtMessages.Text = string.Format("{0} : [{1}] {2}{3}", new object[] { DateTime.Now, level.ToString(), message, this.txtMessages.Text }); return; } } }
private static void JsConsoleMessage(IntPtr data, View caller, MessageSource source, MessageLevel level, string?message, uint number, uint columnNumber, string?id) { Console.WriteLine($"JS_CONSOLE:: {level.ToString()}: {message}"); }
protected void SetMessage(string message, MessageLevel level = MessageLevel.Info) { message = Convert.ToBase64String(Encoding.UTF8.GetBytes(message)); HttpContext.Items[Keys.HttpContextItems.HAS_UI_MESSAGE] = true; Response.Cookies.Set(new HttpCookie(Keys.Cookies.UI_MESSAGE, string.Format("{0}/{1}", level.ToString().ToLowerInvariant(), message))); }
/// <summary> /// Last chance logging if primary logging sink fails. Usually used on application boot strapping. Log file will be located in /// either the file location of Log.LastChangeLogFile or in the default folder of the running application. NOTE: Bypasses /// any configured log provider (log4Net, NLog, TraceLog, etc) and writes directly to text file. Use with extreme care and is /// not configured for high performance. /// </summary> /// <param name="logLevel">Level this message will be logged at</param> /// <param name="message">Text of message</param> /// <param name="args">Arguments to supply to message text (if any)</param> public static void LastChanceLog(MessageLevel logLevel, string message, params object[] args) { string logMessage = ""; try { _lastChanceLock.EnterWriteLock(); if (CoreConfig.Log.IsLastChanceLogEnabled == false) { return; // last chance logging not enabled } logMessage = TextUtils.StringFormat("{0:yyyy-MM-dd HH:mm:ss.fff} {1} {2}", DateTime.Now, logLevel.ToString().ToUpper(), TextUtils.StringFormat(message, args)); File.AppendAllText(CoreConfig.Log.LastChanceLogFile, logMessage + Environment.NewLine); } catch (Exception ex) { try // write to event log if unable to log to last chance file. This is really the last chance of the last chance! { EventLog.WriteEntry("Application Error", string.Format(logMessage, args), EventLogEntryType.Error); EventLog.WriteEntry("Application Error", string.Format(ex.ToString()), EventLogEntryType.Error); } catch (Exception ex2) //couldn't write log to last chance log file or event viewer so swallow exception { System.Diagnostics.Debug.WriteLine(string.Format("Error in LastChanceLog: {0}{1}{2}", ex2.Message, Environment.NewLine, logMessage)); } } finally { _lastChanceLock.ExitWriteLock(); } }
private static string AddPrefix(string Message, MessageLevel Level) { return DateTime.Now + " (" + Level.ToString() + ") " + Message; }