/// <summary> /// Save Log to a txt file. File Path needed in app.config /// </summary> /// <param name="loglevel">Depends on the severity of the log</param> /// <param name="message">Any text the user would like to add</param> /// <param name="exception">Can be null, when logging in trace or debug mode</param> /// <returns>Boolean for unit test purpose</returns> private Boolean File(LogObject loglevel, String message, Exception exception = null) { Boolean response = false; try { if (message == null || message.Length == 0 || loglevel == null) { return(response); } LoggerUtilities.GetLogObject(loglevel, message, exception); String currentPath = String.Format("{0}{1}{2}", MainPath, DateTime.Now.ToShortDateString().Replace("/", "_"), ".txt"); using (StreamWriter logFile = System.IO.File.AppendText(currentPath)) { String logMessage = LoggerUtilities.FormatLogMessage(loglevel); logFile.WriteLine(logMessage); response = true; } } catch (Exception ex) { LoggerUtilities.ShowUnexpectedError("file", ex); } return(response); }
private void CheckItems <T>(LogObject type, Dictionary <string, T> currentItems, Dictionary <string, T> newItems) { DateTime date = DateTime.Now; foreach (KeyValuePair <string, T> pair in newItems) { string key = pair.Key; T state = pair.Value; T oldState; if (!currentItems.TryGetValue(key, out oldState) || !state.Equals(oldState)) { AddEntryUnlocked(new ValueLogEntry(date, type, oldState, state)); currentItems[key] = state; } } List <string> itemsToRemove = new List <string>(); foreach (KeyValuePair <string, T> pair in currentItems) { string key = pair.Key; T state = pair.Value; if (!newItems.ContainsKey(key)) { AddEntryUnlocked(new ValueLogEntry(date, type, state, null)); itemsToRemove.Add(key); } } for (int i = 0; i < itemsToRemove.Count; i++) { currentItems.Remove(itemsToRemove[i]); } }
public GdErrorException(string msg, LogObject logData, ErrorCodeEnum errorCode, string errorName, Exception ex) : base(msg, ex) { LogData = logData; ErrorCode = errorCode; ErrorName = errorName; }
private void Verify(LogObject logObject) { if (string.IsNullOrEmpty(logObject.Name)) { throw new InvalidOperationException($"{nameof(logObject.Name)} cannot be empty"); } }
private async Task LogChangeAsync(Product obj, String action) { ProductLogObj productLogObj = new ProductLogObj { ProductID = obj.ProductID, ProductName = obj.ProductName, UnitPrice = obj.UnitPrice, ProductTypeID = obj.ProductTypeID, ProductTypeName = obj.ProductTypeName.TypeName, ProductTypeDescription = obj.ProductTypeName.Description, ImageName = obj.ImageName }; LogObject logobj = new LogObject { Model = "Product", EntityID = obj.ProductID, Date = DateTime.Now, Action = action, Object = JsonConvert.SerializeObject(productLogObj) }; _context.LogObjects.Add(logobj); await _context.SaveChangesAsync(); }
public LogEntry(String msg, String sub, LogObject obj, LogEntry[] inners = null) { SubInfo = sub; Message = msg; Object = obj; InnerMessages = inners; }
private string WriteLogEntry(List <object> curObjects, string logMessage, LogLevelType curLevel, Exception curException, string destinationMachineName, string applicationName, string uniqueId, string winUser, string tenantId) { if (string.IsNullOrEmpty(uniqueId)) { uniqueId = Guid.NewGuid().ToString(); } var nLogLevel = LogLevel.FromString(curLevel.ToString()); var curLogObject = new LogObject { Message = logMessage, CurrentDataObjects = curObjects }; string message; switch (_type) { case SerializerType.Json: message = JsonConvert.SerializeObject(curLogObject); break; case SerializerType.Xml: using (var sw = new StringWriter()) { _curSerializer.Serialize(sw, curLogObject); message = sw.ToString(); } break; default: throw new ArgumentOutOfRangeException("_type"); } var logRecord = curException != null ? new LogEventInfo(nLogLevel, null, null, message, null, curException) : new LogEventInfo(nLogLevel, null, message); logRecord.Properties["DestinationMachineName"] = destinationMachineName; logRecord.Properties["UniqueID"] = uniqueId; logRecord.Properties["TenantId"] = tenantId; if (!string.IsNullOrEmpty(applicationName)) { logRecord.Properties["AppCode"] = applicationName; } else { logRecord.Properties["AppCode"] = Process.GetCurrentProcess().ProcessName; } if (!string.IsNullOrEmpty(winUser)) { logRecord.Properties["WinUser"] = winUser; } else { logRecord.Properties["WinUser"] = System.Security.Principal.WindowsIdentity.GetCurrent().Name; } _curLogger.Log(logRecord); return(uniqueId); }
public JournalViewModel() { JournalEvents = journal.GetJournal(); LogObject.GetAllLogObjects(); RefreshJournal = new CustomModelCommand <JournalEvent>((c) => { JournalEvents = journal.GetJournal(); RaiseEvent(nameof(JournalEvents)); }); FilterJournal = new CustomModelCommand <string>((s) => { if (SelectedCondition != null) { switch (SelectedCondition) { case "Дата": DateTime inputDateTime = new DateTime(); if (DateTime.TryParse(s, out inputDateTime)) { FilteredJournalEvents = JournalEvents.Where((e) => e.DateTime.Date == inputDateTime.Date).ToList(); } break; case "По объектам": FilteredJournalEvents = JournalEvents.Where((e) => e.Info.Contains(s)).ToList(); break; } } }); }
private void BuildLogAndSendCommand(string message, string type) { LogObject newLog = new LogObject(type, message); var serializedLog = JsonConvert.SerializeObject(newLog); CommandRecievedEventArgs cmd = new CommandRecievedEventArgs((int)CommandEnum.LogCommand, new string[] { serializedLog }, String.Empty); this.communicator.SendCommandBroadCast(cmd); }
private async Task LogChangeAsync(AppUser obj, String action) { var user = new { Username = obj.UserName, Email = obj.Email, Fullname = obj.UserName, Address = obj.Address, Type = obj.Type, EmailConfirmed = obj.EmailConfirmed, PhoneNumber = obj.PhoneNumber, TwoFactorEnabled = obj.TwoFactorEnabled }; LogObject logobj = new LogObject { Model = "Account", EntityID = obj.Id, Date = DateTime.Now, Action = action, Object = JsonConvert.SerializeObject(user) }; _context.LogObjects.Add(logobj); await _context.SaveChangesAsync(); }
public void TestLoggerEncryption() { var result = LoggerHelper.CreateLogger("Deim Vadder sein Service", null, null); var logger = result.logger; dynamic logResult = new ExpandoObject(); bool exceptionThrown = false; try { LoggerHelper.CreateTraceObject("das ist ein verschlüsselter test", true, "Köaäasdaspfe"); } catch (FormatException) { exceptionThrown = true; } Assert.True(exceptionThrown); var keyPair = PublicKeyBox.GenerateKeyPair(); var traceObject = LoggerHelper.CreateTraceObject("das ist ein verschlüsselter test", true, Convert.ToBase64String(keyPair.PublicKey)); logger.LogTrace(traceObject); var message = result.loggerProvider.Messages[0].Message; Encrypter dec = new AsymmetricEncrypter(keyPair.PrivateKey); JToken content = JObject.Parse(message).GetValue("Content"); EncryptedObject eo = JsonConvert.DeserializeObject <EncryptedObjectPublicKeyBox>(content.ToString()); BusinessObject bo = dec.Decrypt(eo); Assert.NotNull(bo); Assert.Equal(1, bo.VersionStruktur); LogObject lo = bo as LogObject; Assert.Equal("das ist ein verschlüsselter test", lo.LogMessage); }
private static async Task <WitsmlWellbore> GetWellbore(IWitsmlClient client, LogObject logObject) { var query = WellboreQueries.QueryByUid(logObject.WellUid, logObject.WellboreUid); var wellbores = await client.GetFromStoreAsync(query, OptionsIn.Requested); return(!wellbores.Wellbores.Any() ? null : wellbores.Wellbores.First()); }
public static void FindAllSprites() { LogObject SpriteLog = new LogObject("SpriteLoader"); // First, we need to list all files on SPRITES directory string[] AllSprites = Directory.GetFiles(Global.IMAGE_SourceFolder, "*.png", SearchOption.AllDirectories); SpriteLog.Write(Utils.ConsoleWriteWithTitle("SpriteLoader", "Listing all sprites...")); foreach (var file in AllSprites) { FileInfo info = new FileInfo(file); string FileFullName = info.FullName; string SpriteFiltedName = FileFullName.Replace(Environment.CurrentDirectory, ""); SpriteFiltedName = SpriteFiltedName.Replace(Global.IMAGE_SourceFolder + "\\", "").Replace("\\", "/"); int SpriteID = AllSpritedLoaded_Names.IndexOf(SpriteFiltedName); if (SpriteID == -1 && info.Extension == ".png") { AllSpritedLoaded_Content.Add(LoadTexture2D_FromFile(FileFullName)); AllSpritedLoaded_Names.Add(SpriteFiltedName); SpriteLog.Write(Utils.ConsoleWriteWithTitle("SpriteLoader", "Found [" + SpriteFiltedName + "].")); } } SpriteLog.Write(Utils.ConsoleWriteWithTitle("SpriteLoader", "Operation Completed")); SpriteLog.FinishLog(false); }
private static LogEntry WrapObject <T>(ulong type, ulong version, T inner, byte[] previousHash) where T : ILogSerialized { var @object = new LogObject { Timestamp = TimestampFactory.Now, Type = type, Version = version, Data = inner }; @object.Hash = HashProvider.ComputeHashBytes(@object); var entry = new LogEntry { PreviousHash = previousHash, Timestamp = @object.Timestamp, Nonce = Crypto.Nonce(64U), Objects = new[] { @object } }; entry.HashRoot = HashProvider.ComputeHashRootBytes(entry); entry.Hash = HashProvider.ComputeHashBytes(entry); return(entry); }
public override void EndOperationTransaction(EndOperationTransactionArgs e) { base.EndOperationTransaction(e); if (e.DataEntitys.Length == 0) { return; } var dataObj = e.DataEntitys[0]; var strDesc = string.Format("保存插件测试,单据编号为:{0},采购日期为:{1}的采购订单保存成功!" , dataObj["BillNo"], dataObj["Date"]); LogObject logObj = new LogObject() { pkValue = dataObj["Id"].ToString(), Description = strDesc, OperateName = this.FormOperation.OperationName, ObjectTypeId = this.BusinessInfo.GetForm().Id, SubSystemId = this.BusinessInfo.GetForm().SubsysId, Environment = OperatingEnvironment.BizOperate }; ILogService logService = ServiceHelper.GetService <ILogService>(); logService.WriteLog(this.Context, logObj); }
private static void LogMessage(LogObject logObject) { _log.Add(logObject); var message = logObject.ToString(); if (logObject.Type == MessageType.Error) { Trace.TraceError(message); } else if (logObject.Type == MessageType.Warning) { Trace.TraceWarning(message); } else { Trace.TraceInformation(message); } if (Out != null) { try { Out.WriteLine(message); Out.Flush(); } catch (Exception e) { Trace.TraceError("Unable to write to the log output stream: {0}", e); Out = null; } } MessageLogged?.Invoke(logObject); }
public Task HandleLogAsync(LogObject log, string sessionId) { if (log.LogType == ELogType.Error) { System.Console.ForegroundColor = ConsoleColor.Red; } else if (log.LogType == ELogType.Warning) { System.Console.ForegroundColor = ConsoleColor.Yellow; } System.Console.WriteLine(); System.Console.WriteLine(DefaultLogReceivedMessage); System.Console.WriteLine($"\t{log.LogType} - {log.Source} - {log.TimeStamp}"); System.Console.WriteLine($"\t{log.Message}"); if (log.Parameters != null) { foreach (var para in log.Parameters) { System.Console.WriteLine($"\t\t[{para.Key}] => {para.Value}"); } } System.Console.WriteLine(); System.Console.ResetColor(); return(Task.CompletedTask); }
//新增显示单行消息 public void AddMessage(LogObject logObject) { string str = ""; switch (logObject.type) { case LogType.Info: str = logObject.text; break; case LogType.ProduceDone: str = gc.districtDic[logObject.value[0]].baseName + "的" + gc.buildingDic[logObject.value[1]] + "生产了" + gc.itemDic[logObject.value[2]]; break; case LogType.BuildDone: str = gc.districtDic[logObject.value[0]].baseName + "的" + gc.buildingDic[logObject.value[1]] + "建造完成了"; break; default: str = "未定义日志类型"; break; } GameObject go; go = Instantiate(Resources.Load("Prefab/UILabel/Label_Message")) as GameObject; go.transform.SetParent(messageListGo.transform); go.GetComponent <RectTransform>().anchoredPosition = new Vector3(0f, count * 16f, 0f); go.transform.GetChild(0).GetComponent <Text>().text = str; if (logObject.value[0] != -1) { go.GetComponent <InteractiveLabel>().index = logObject.id; } else { go.transform.GetChild(1).localScale = Vector3.zero; } messageListGo.transform.GetComponent <RectTransform>().sizeDelta = new Vector2(313f, 16f + count * 16f); count++; messageSb.value = 1f; }
private void WriteToCache(LogObject logObject) { if (this._FlushTimer == null) { this._FlushTimer = new Timer( new TimerCallback(this.FlushInternal), null, (this._FlushCycle * 60000), 0 ); } Monitor.Enter(this._LogCacheSyncObject); try { TimeSpan totalSpan = System.DateTime.Now.Subtract(new System.DateTime(2000, 1, 1, 0, 0, 0)); this._LogCache.Add(totalSpan.Ticks, logObject); // wait to prevent Ticks equality Thread.Sleep(1); } finally { Monitor.Exit(this._LogCacheSyncObject); } if (this._LogCache.Count >= this._LogCacheLimit) { ThreadPool.QueueUserWorkItem(new WaitCallback(this.FlushInternal)); } }
public ValueLogEntry(DateTime date, LogObject type, object previous, object current) { Date = date; Type = type; PreviousValue = previous; CurrentValue = current; }
public async Task Write_speed() { var inner = new Namespace("Benchmark"); var @object = new LogObject { Timestamp = new UInt128(0UL, (ulong)DateTimeOffset.Now.ToUnixTimeSeconds()), Type = _typeProvider.Get(typeof(Namespace)), Version = 1, Data = inner }; @object.Hash = _hashProvider.ComputeHashBytes(@object); var entry = new LogEntry { PreviousHash = _previousHash, Timestamp = @object.Timestamp, Nonce = Crypto.Nonce(64U), Objects = new[] { @object } }; entry.HashRoot = _hashProvider.ComputeHashRootBytes(entry); entry.Hash = _hashProvider.ComputeHashBytes(entry); await _store.AddEntryAsync(entry); _previousHash = entry.Hash; }
public static void OptionLine(string[] Input, LogObject CurrentLog) { foreach (var option in Input) { Console.WriteLine("Received Option (" + option + ")"); CurrentLog.Write(Utils.ConsoleWriteWithTitle("TaiyouLineRevision", "LineRevision Completed")); } }
public LoggingEventEventArgs(LogObject loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } LoggingEvent = loggingEvent; }
public byte[] Serialize(LogObject log) { byte[] output = null; output = serializer.Serialize(log); return output; }
private void LogEvent(int pos, int length) { LogObject o = new LogObject(); o.pos = pos; o.length = length; Logfile.Add(o); }
public static LogObject GetLogObject(LogObject logLevel, String message, Exception exception) { LogObject logObject = logLevel; logObject.Message = message; logObject.Ex = exception; return(logObject); }
private void ReadModule(ref List <BsonDocument> Datastreams, ref long ReqTime, Action <int, dynamic> Callback, IPlc PLC) { long TimeStamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; LogObject logObj; Stopwatch watch = new Stopwatch(); foreach (BsonDocument Stream in Datastreams) { Stream["oldTime"] = 0; } Callback(1, Datastreams); watch.Start(); long Req = 0; while (true) { Callback(0, null); TimeStamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; watch.Restart(); foreach (BsonDocument Stream in Datastreams) { try { if (BsonResolver.Resolve(Stream["Active"]) && BsonResolver.Resolve(Stream["Interval"]) <= TimeStamp - BsonResolver.Resolve(Stream["oldTime"])) { byte[] buffer = GetBuffer(BsonResolver.Resolve(Stream["DataType"])); PLC.Read(Stream, ref buffer); logObj = new LogObject(); logObj.PLC = BsonResolver.Resolve(PLC.ClientDetails["id"].ToString()); logObj.Datastream = BsonResolver.Resolve(Stream["Collection"]) + "_" + BsonResolver.Resolve(Stream["id"]); logObj.Value = buffer; logObj._ts = TimeStamp; logObj.DataType = BsonResolver.Resolve(Stream["DataType"]); logObj.Position = BsonResolver.Resolve(Stream["Position"]); Queue.Enqueue(logObj); Stream["oldTime"] = TimeStamp; } } catch { PLC.Disconnect(); while (!PLC.Connect()) { Thread.Sleep(1000); } } } Req = watch.ElapsedMilliseconds; if (Req > 0) { ReqTime = Req; } } }
public LogObject Deserialize(byte[] bytes) { LogObject output = null; string[] logElems = Encoding.ASCII.GetString(bytes).Split(' '); try { #region <PRIVAL> + DATE {logElems[0..n]}, n = 2 || 3 string[] logHead = logElems[0].Split('>'); double priority = Double.Parse(logHead[0].Replace("<", string.Empty)); int facility = (int)Math.Floor(priority / (double)8); int severity = (int)(priority - 8 * facility); string dateStr = string.Format("{0} {1} {2} {3}", logElems[1].Length.Equals(2) ? logElems[1] : logElems[2], logHead[1], DateTime.Now.Year, logElems[1].Length.Equals(2) ? logElems[2] : logElems[3]); DateTime date = DateTime.Parse(dateStr); Dictionary<string, object> properties = new Dictionary<string, object>(); properties.Add("facility", facility); properties.Add("severity", severity); #endregion #region HOSTNAME {logElems[x]}, x = 3 | 4 string hostname = logElems[1].Length.Equals(2) ? logElems[3] : logElems[4]; #endregion #region MESSAGE {logElems[x..logElems.Length]}, x = 4 | 5 int index = logElems[1].Length.Equals(2) ? 4 : 5; string message = string.Empty; for (int i = index; i < logElems.Length; i++) message += logElems[i] + (logElems[i].Equals(logElems.Last()) ? string.Empty : " "); #endregion output = new LogObject() { Host = hostname, Message = message, Timestamp = date, Level = Severity2Level(severity), Namespace = hostname }; } catch (Exception e) { throw new SerializationException("Error during Syslog deserialization", bytes, e); } return output; }
private static void Log(LogType logType, LogObject obj) { try { SetPaths(logType, out StringBuilder dirPath, out string path); if (!Directory.Exists(dirPath.ToString())) { Directory.CreateDirectory(dirPath.ToString()); } string fileInfo; if (File.Exists(path)) { using (StreamReader sr = new StreamReader(path)) { fileInfo = sr.ReadToEnd(); } } else { fileInfo = ""; } Log logObjects = new Log(); try { logObjects = Newtonsoft.Json.JsonConvert.DeserializeObject <Log>(fileInfo) ?? new Log(); } catch (Exception e) { Console.WriteLine(e.Message + ":" + e.StackTrace); } finally { logObjects.LogObjects.Add(obj); using (StreamWriter sw = File.CreateText(path)) { if (logObjects.LogObjects.Count == 0) { logObjects.LogObjects.Add(new LogObject("Could not add logObjects. Is there a difference in versioning? Overwriting previous log.")); } string json = Newtonsoft.Json.JsonConvert.SerializeObject(logObjects); sw.Write(json); } } } catch (Exception e) { new JsonLogger().LogError(e.Message); } }
public static void Log(String message, LogObject obj) { m_messageBuffer.Post(new LogEntry { Message = message, Object = obj }); m_logger.Info(message); }
private static string TaiyouParserError(string Message, LogObject CurrentLog) { string Result = "Error while parsing the Taiyou Script\n" + Message; CurrentLog.Write(Utils.ConsoleWriteWithTitle("Taiyou_Parser_Error", "\n" + Result)); CurrentLog.FinishLog(false); return(Result); }
protected void UpdateLogs(bool success, string message) { LogObject log = new LogObject(message, success); logger.Log(log); if (!success && Settings.Default.ShowMessages) { MessageBox.Show("Fail or error: " + message); } }
public void AddObject(LogObject newItem) { //Find blank spot for (var i = 0; i < _items.Count; i++) { if (_items[i] == null) { _items[i] = newItem; return; } } // Add to end if we didnt find a blank spot; _items.Add(newItem); }
public void LogCustom(LogObject logObj) { int id = Thread.CurrentThread.ManagedThreadId; string remark = logObj.When.ToString() + " [id : " + id.ToString() + "]"; LogObject obj = new LogObject(logObj.Level, logObj.Msg, remark); System.IO.File.AppendAllText("threadstate.log", obj.ToString("\t"), System.Text.Encoding.UTF8); }
public void CreateDibPatternBrush(LogObject brush) { _objectTable.AddObject(brush); }
public void CreatePalette(LogObject palette) { _objectTable.AddObject(palette); }
public void Forward(LogObject log) { this.Forward(new LogObject[] { log }); }
/// <summary> /// Logs the specified object as string. /// </summary> /// <param name="o"></param> /// <returns>True if the object was logged; otherwise false.</returns> public bool Log(LogObject o) { StringBuilder b = new StringBuilder(256); string flags = string.Empty; if (o.Flags != 0) flags = "|" + o.Flags.ToString(); string sources = string.Empty; if (!this.SourceExcluded && o.Sources.Count > 0) sources = " @ " + string.Join("/", o.Sources); b.AppendFormat(this.HeaderFormatString, o.Timestamp, o.Priority, flags, sources); string indent = this.Indentation[o.Indent]; string margin = Indentation.OneSpace[b.Length]; for (int i = 0; i < o.Payloads.Count; i++) { if (i > 0) { b.AppendLine(); b.Append(margin); } var pld = o.Payloads[i]; switch (pld.GetType().GetPayloadType()) { case PayloadTypes.Message: var pldm = (MessagePayload)pld; b.AppendFormat("<{0,-11}> ", pldm.MessageType); var extraMargin = Indentation.OneSpace[14]; // Compensates for the text above. var msplit = pldm.Message.Split('\n'); for (int j = 0; j < msplit.Length; j++) { if (j > 0) { b.Append(margin); b.Append(extraMargin); } b.Append(indent); b.AppendLine(msplit[j].Trim('\r')); } break; case PayloadTypes.Exception: var plde = (ExceptionPayload)pld; for (int j = 0; j < plde.Exceptions.Count; j++) { if (j > 0) { b.AppendLine(); b.Append(margin); } var explit = plde.Exceptions[j].Split('\n'); for (int k = 0; k < explit.Length; k++) { if (k > 0) b.Append(margin); b.Append(indent); b.AppendLine(explit[k].Trim('\r')); } } break; case PayloadTypes.KeyValue: var pldkv = (KeyValuePayload)pld; _KVPs(b, pldkv.Collection, o.Indent, margin, string.Empty); break; default: return false; } } return Log(o, b.ToString()); }
public byte[] Serialize(LogObject log) { byte[] output; try { #region PRIVAL int faclity = 0; int priority = Level2Severity(log.Level) + faclity * 8; string PRIVAL = priority.ToString(); #endregion #region VERSION string VERSION = "0"; #endregion #region DATE string DATE = log.Timestamp.ToUniversalTime().ToString("o"); #endregion #region HOSTNAME string HOSTNAME = log.Host; #endregion #region APPNAME string APPNAME = log.Namespace; #endregion #region PROCID string PROCID = log.Properties == null || log.Properties["procid"] == null ? "-" : log.Properties["procid"] as string; #endregion #region MSGID string MSGID = "-"; #endregion #region STRUCTUREDDATA List<string> invalidKeys = new List<string>() { "procid" }; string STRUCTUREDDATA = string.Empty; if(log.Properties != null) foreach (KeyValuePair<string, object> pair in log.Properties) { string key = pair.Key; string value = pair.Value as string; if (!invalidKeys.Contains(key)) STRUCTUREDDATA += string.Format("{0}={1} ", key, value); } if (string.IsNullOrEmpty(STRUCTUREDDATA)) STRUCTUREDDATA = "-"; else STRUCTUREDDATA = string.Format("[{0}]", STRUCTUREDDATA.Substring(0, STRUCTUREDDATA.Length - 1)); #endregion #region MESSAGE string MESSAGE = string.Format("{0}", log.Message); #endregion string logStr = string.Format("<{0}>{1} {2} {3} {4} {5} {6} {7} {8}", PRIVAL, VERSION, DATE, HOSTNAME, APPNAME, PROCID, MSGID, STRUCTUREDDATA, MESSAGE); output = this.Encoding.GetBytes(logStr); } catch (Exception e) { throw new SerializationException("Error during Syslog serialization", log, e); } return output; }
public void AddObject(LogObject newItem) { _objectTable.AddObject(newItem); }
public LogObject Deserialize(byte[] bytes) { LogObject output = null; string[] logElems = Encoding.ASCII.GetString(bytes).Split(' '); try { #region <PRIVAL> + VERSION {logElems[0]} string[] logHead = logElems[0].Split('>'); double priority = Double.Parse(logHead[0].Replace("<", string.Empty)); int facility = (int)Math.Floor(priority / (double)8); int severity = (int)(priority - 8 * facility); int version = Int32.Parse(logHead[1]); #endregion #region DATE {logElems[1]} DateTime date = DateTime.Parse(logElems[1]); #endregion #region HOSTNAME {logElems[2]} string hostname = logElems[2]; #endregion #region APPNAME {logElems[3]} string appname = logElems[3]; #endregion #region PROCID {logElems[4]} string procid = logElems[4]; #endregion #region MSGID {logElems[5]} string msgid = logElems[5]; #endregion #region STRUCTUREDDATA {logElems[6..n]} Dictionary<string, object> structureddata = new Dictionary<string, object>(); int n = 6; List<string> sdata = new List<string>(); if (!logElems[6].Length.Equals(1)) { bool stop = true; string sd_element = string.Empty; for (int i = n; ; i++, n++) { if (i.Equals(logElems.Length) || stop && !logElems[i].Contains("[")) break; else if (!stop && logElems[i].Contains("]")) { if (logElems[i].Split(']').Length.Equals(2) && logElems[i].Split(']')[1].Length.Equals(0)) { sd_element += logElems[i]; stop = true; } else sd_element += logElems[i].Split(']')[0]; sdata.Add(sd_element); sd_element = string.Empty; } else { sd_element += string.Format("{0} ", logElems[i]); stop = false; } } if (!sdata.Count.Equals(0)) { sdata.ForEach( elem => { string sdelementraw = elem.Replace("[", string.Empty).Replace("]", string.Empty); //remove '[' character string sdelement = sdelementraw.Replace(string.Format("{0} ", sdelementraw.Split(' ')[0]), string.Empty); //remove 'SD-ID' from several elements List<string> sdpairs = sdelement.Split(' ').ToList(); foreach (string pair in sdpairs) { string[] element = pair.Split('='); string param = element[0]; string value = element[1]; structureddata.Add(param, value); } }); } } else n++; if (!procid.Equals("-")) structureddata.Add("procId", procid); #endregion #region MESSAGE {logElems[n..logElems.Length]} string message = string.Empty; bool encoding = false; if (!n.Equals(logElems.Length)) { encoding = logElems[n].Length >= 3 && logElems[n].Substring(0, 3).Equals("BOM"); //FIXME USAR ISTO PARA DEFINIR O ENCODING for (int i = n; i < logElems.Length; i++) { string tmp = i.Equals(n) && encoding ? logElems[n].Substring(3, logElems[n].Length - 3) : logElems[i]; message += string.Format("{0}{1}", tmp, logElems[i].Equals(logElems.Last()) ? string.Empty : " "); } } #endregion output = new LogObject() { Host = hostname, Message = message, Timestamp = date, Level = Severity2Level(severity), Properties = structureddata, Namespace = appname }; } catch (Exception e) { throw new SerializationException("Error during Syslog deserialization", bytes, e); } return output; }
public void LogCustom(LogObject logObj) { System.IO.File.AppendAllText(_baseDir + "log.log", logObj.ToString("\t"), Encoding.UTF8); }
public byte[] Serialize(LogObject log) { byte[] output = null; try { #region PRIVAL int faclity = 0; int priority = Level2Severity(log.Level) + faclity * 8; string PRIVAL = priority.ToString(); #endregion #region DATE string DATE = log.Timestamp.ToUniversalTime().ToString("MMM dd HH:mm:ss"); #endregion #region HOSTNAME string HOSTNAME = log.Host; #endregion #region MSG string MSG = log.Message; #endregion string logStr = string.Format("<{0}>{1} {2} {3}", PRIVAL, DATE, HOSTNAME, MSG); output = Encoding.ASCII.GetBytes(logStr); } catch (Exception e) { throw new SerializationException("Error during Syslog serialization", log, e); } return output; }
/// <summary> /// Partitions the given log object. /// </summary> /// <param name="o"></param> /// <param name="b"></param> /// <returns>A <see cref="System.String"/> representing a relative file path where the object will be stored; null if not stored.</returns> public virtual string Partition(LogObject o) { return this.File; }
public void CreatePatternBrush(LogObject patBrush) { _objectTable.AddObject(patBrush); }
public void CreateRegion(LogObject region) { _objectTable.AddObject(region); }
/// <summary> /// Logs the specified string representing a <see cref="vLogs.Objects.LogObject"/>. /// </summary> /// <param name="o"></param> /// <param name="s"></param> /// <returns>True if the object was logged; otherwise false.</returns> protected abstract bool Log(LogObject o, string s);