public void WriteLog(string strLog, LogCode logCode)
        {
            try
            {
                _con.Open();

                var transaction = _con.BeginTransaction();

                var command = _con.CreateCommand();
                command.CommandType = System.Data.CommandType.Text;
                command.CommandText = "";
                command.Parameters.AddRange(new SqlParameter[]
                {
                    new SqlParameter {
                        ParameterName = "LogText", Value = strLog
                    },
                    new SqlParameter {
                        ParameterName = "LogCode", Value = logCode.ToString()
                    }
                });
                command.ExecuteNonQuery();

                transaction.Commit();
            }
            catch
            {
                throw;
            }
            finally
            {
                _con.Close();
            }
        }
Exemple #2
0
        public static void WriteLog(string strLog, LogCode logCode, string strFileName, string strPath)
        {
            string strFullName;

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

            if (strPath.EndsWith(@"\") == false || strPath.EndsWith("/") == false)
            {
                strPath = strPath + @"\";
            }

            strFullName = strPath + strFileName + "_" + DateTime.Now.ToString(DateTimeFormet) + ".txt";

            string strFullLog = DateTime.Now.ToString("HH:mm:ss") + " (" + logCode.ToString() + ")" + " : " + strLog;

            lock (asyncObject)
            {
                using (StreamWriter sw = new StreamWriter(strFullName, true, System.Text.Encoding.UTF8, 4096))
                {
                    sw.WriteLine(strFullLog);
                    sw.Close();
                }
            }
        }
Exemple #3
0
        private void Initialise(LogCode logCode, string[] interpolations)
        {
            // Log the exception.
            Logger.Log(logCode, interpolations);

            // Exit with error code 1. Anything that isn't zero should be fairly conventional here.
            Environment.Exit(1);
        }
 public void Info(LogCode code, params string[] messages)
 {
     if (items == null)
     {
         items = new List <LogItem>();
     }
     items.Add(new LogItem(LogType.Log, code, messages));
 }
 public StandardLog(LogCode logCode)
 {
     this.userName = Environment.UserName;
     this.dtUtc    = DateTime.UtcNow;
     this.dt       = DateTime.Now;
     this.hostName = Dns.GetHostName();
     this.localIP  = Dns.GetHostEntry(hostName).AddressList.GetValue(0).ToString();
     this.logCode  = logCode;
 }
Exemple #6
0
        public async Task Log(LogCode code, string message, SocketMessage messageInfo = null)
        {
            if (message.Length > 2000)
            {
                return;
            }
            var color = Color.Green;

            switch (code)
            {
            case LogCode.error:
                color = Color.Red;
                break;

            case LogCode.warning:
                color = Color.Orange;
                break;

            case LogCode.debug:
                color = Color.Blue;
                break;

            case LogCode.message:
                color = Color.Green;
                break;

            case LogCode.fatal_error:
                color   = Color.DarkRed;
                message = "<@138439306774577152> \n" + message;
                break;
            }

            var embedbuilder = new EmbedBuilder
            {
                Title       = code.ToString(),
                Description = message,
                Color       = color,
                Footer      = new EmbedFooterBuilder()
                {
                    Text = DateTime.Now.ToString()
                }
            };

            //Console.WriteLine(embedbuilder.Title + "\n\n" + embedbuilder.Description);
            try
            {
                await _discord.GetGuild(505485680344956928).GetTextChannel(592877335355850752).SendMessageAsync("", false, embedbuilder.Build());

                //await _discord.GetGuild(677437721081413633).GetTextChannel(682874265594363916).SendMessageAsync("", false, embedbuilder.Build());
            }
            catch
            {
                Console.WriteLine("No Internet connection");
            }
        }
Exemple #7
0
        public virtual LogResult Process()
        {
            string  result    = String.Empty;
            string  timestamp = String.Empty;
            LogCode code      = LogCode.LOG_NOTHING;
            Match   logMatch;

            result = this.m_streamReader.ReadLine();
            if (result != null && result != String.Empty)
            {
                logMatch = Regex.Match(result, LogReader.logHeaderPattern, RegexOptions.IgnorePatternWhitespace);
                if (logMatch.Success)
                {
                    result    = logMatch.Groups["MESSAGE"].Value;
                    timestamp = logMatch.Groups["DATE"].Value + " " + logMatch.Groups["TIME"].Value;;
                    code      = LogCode.LOG_EVENT;
                }
                else
                {
                    if (Regex.Match(result, LogReader.logModelingPattern, RegexOptions.IgnorePatternWhitespace).Success)
                    {
                        LogReader.s_isModeling = !LogReader.s_isModeling;
                    }
                    if (LogReader.s_isModeling)
                    {
                        if (csmevent != null)
                        {
                            if (String.IsNullOrEmpty(csmevent.eventInfo.Modeling))
                            {
                                csmevent.eventInfo.Modeling += result;
                            }
                            else
                            {
                                csmevent.eventInfo.Modeling += Environment.NewLine + result;
                            }
                            code = LogCode.LOG_MODELING;
                        }
                        else
                        {
                            code = LogCode.LOG_NOTHING;
                        }
                    }
                }
            }
            else if (result == null)
            {
                code = LogCode.LOG_EOF;
            }
            return(new LogResult(code, result, timestamp));
        }
Exemple #8
0
        public void Log(LogLevel level, LogCode code, params object[] args)
        {
            object toSerialize = args;

            if (args.Length == 1)
            {
                toSerialize = args[0];
            }

            var argsJson = JsonConvert.SerializeObject(toSerialize, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
            });

            string line = $"[{level}] : {code.GetDescription()}. Parameters: {argsJson}";

            Trace.WriteLine(line);
        }
Exemple #9
0
        /// <summary>
        /// 增加日志
        /// </summary>
        /// <param name="code">日志编码</param>
        /// <param name="newsId">新闻Id</param>
        /// <param name="remark">备注</param>
        /// <param name="beforeJson"></param>
        /// <param name="afterJson"></param>
        public void Add_Log(LogCode code, string newsId, string userId, string remark = null, string beforeJson = null, string afterJson = null, string info = null)
        {
            using (DbRepository db = new DbRepository())
            {
                var model = new Log();
                model.ID          = Guid.NewGuid().ToString("N");
                model.NewsID      = newsId;
                model.AdminID     = userId;
                model.CreatedTime = DateTime.Now;
                model.Remark      = remark;
                model.Code        = code;
                model.BeforeJson  = beforeJson;
                model.AfterJson   = afterJson;
                model.UpdateInfo  = info;
                db.Log.Add(model);

                db.SaveChanges();
            }
        }
Exemple #10
0
 public void SaveLogToCassandra(string log, LogCode logCode, TypeLog typeLog, long data_id = 0, long data_second_id = 0, log4net.ILog iLogNet = null, string session = "")
 {
     if (iLogNet != null)
     {
         iLogNet.Info(log);
     }
     try
     {
         if (session == "")
         {
             session = Guid.NewGuid().ToString();
         }
         DateTime dateLog = DateTime.Now;
         string   id      = Guid.NewGuid().ToString();
         string   str     = string.Format(this.queryUpdateProduct,
                                          Guid.NewGuid().ToString()
                                          , data_id.ToString()
                                          , data_second_id.ToString()
                                          , "'" + log + "'"
                                          , (int)typeLog
                                          , string.Format("'{0}'"
                                                          , dateLog.ToString("yyyy-MM-dd HH:mm:ss"))
                                          , (int)logCode
                                          , QT.Entities.Common.Obj2Int64(dateLog.ToString("yyyyMMdd").ToString())
                                          , session);
         this._session.Execute(str, ConsistencyLevel.Any);
         if ((int)logCode == 6)
         {
             logCrawler.Info("Insert mss 6");
             bool bOK = sqldb.RunQuery("INSERT INTO Company_LogCrawler (CompanyID, DateLog, session, logCode) VALUES (@CompanyID,@DateLog,@session,@logCode)", CommandType.Text, new System.Data.SqlClient.SqlParameter[] {
                 sqldb.CreateParamteter("@CompanyID", data_id, SqlDbType.BigInt),
                 sqldb.CreateParamteter("@DateLog", dateLog, SqlDbType.DateTime),
                 sqldb.CreateParamteter("@session", session, SqlDbType.VarChar),
                 sqldb.CreateParamteter("@logCode", (int)logCode, SqlDbType.Int)
             });
             logCrawler.InfoFormat("Insert mss ok :{0}", bOK.ToString());
         }
     }
     catch (Exception ex01)
     {
         iLogNet.Error(ex01);
     }
 }
Exemple #11
0
        /// <summary>
        /// 增加日志
        /// </summary>
        /// <param name="code">日志编码</param>
        /// <param name="studentId">学员Id</param>
        /// <param name="remark">备注</param>
        /// <param name="beforeJson"></param>
        /// <param name="afterJson"></param>
        public void Add_Log(LogCode code, string studentId, string remark, string beforeJson, string afterJson, string info)
        {
            using (DbRepository entities = new DbRepository())
            {
                var model = new Log();
                model.ID = Guid.NewGuid().ToString("N");

                model.CreatedTime = DateTime.Now;
                model.CreaterID   = Client.LoginUser.ID;
                model.Remark      = remark;
                model.Code        = code;
                model.BeforeJson  = beforeJson;
                model.AfterJson   = afterJson;
                model.StudentID   = studentId;
                model.UpdateInfo  = info;
                entities.Log.Add(model);

                entities.SaveChanges();
            }
        }
Exemple #12
0
        public static string FormatMessage(LogCode logCode, params object[] args)
        {
            LogMessage logMessage;

            if (!LogMessageDictionary.TryGetValue(logCode.ToString(), out logMessage))
            {
                throw new ApplicationException($"Log message is not defined for log code: {logCode}.");
            }

            try
            {
                string message = string.Format(logMessage.Message, args);
                return(string.IsNullOrEmpty(message) ? logCode.ToString() : message);
            }
            catch (FormatException fe)
            {
                var argsString = args == null ? "<null>" : string.Join(", ", args);
                throw new ApplicationException($"Log message {logMessage} for log code {logCode} has less paramters than provided {argsString}", fe);
            }
        }
Exemple #13
0
        public void SaveLog(string log, LogCode logCode, TypeLog typeLog, long data_id = 0, long data_second_id = 0, log4net.ILog iLogNet = null, string session = "")
        {
            if (iLogNet != null)
            {
                iLogNet.Info(log);
            }
            Job job = new Job()
            {
                Data = new QT.Entities.CrawlerProduct.RabbitMQ.MssLogCassandra()
                {
                    data_id        = data_id,
                    data_second_id = data_second_id,
                    log            = log,
                    logCode        = (int)logCode,
                    session        = session,
                    typeLog        = (int)typeLog
                }.ToMss(),
                Type = 0
            };
            int CountFail = 0;

            while (true)
            {
                try
                {
                    jobClient.PublishJob(job, 0);
                    CountFail++;
                    break;
                }
                catch (Exception ex01)
                {
                    iLogNet.Error(ex01);
                    if (CountFail > 5)
                    {
                        break;
                    }
                }
            }
        }
        public bool Log(XeroApi.Model.Invoice anInvoice, InterResolveXeroService theService, LogCode Code)
        {
            //compose a line and write to file

            StreamWriter sw = new StreamWriter();

                //success
                if(Code == LogCode.OK)
                {
                    sw = File.AppendText(SuccessLogFileName + LogFilePath);

                }

                //fail
                else if (Code == LogCode.FAIL)
                {
                    sw = File.AppendText(FailureLogFileName + LogFilePath);
                    sw.WriteLine("Type:" + anInvoice.Type + "Company:" + theService.CompanyName + "Invoice Number:" + anInvoice.InvoiceNumber + " : " + "Ref:" + anInvoice.Reference + "Date:" + DateTime.Now + "NoOfErrors" + anInvoice.ValidationErrors.Count);
                }

            return true;
        }
Exemple #15
0
        public static string GetFullMessage(LogCode code, params string[] messages)
        {
#if GLTFAST_REPORT
            return(messages != null
                ? string.Format(fullMessages[code], messages)
                : fullMessages[code]);
#else
            if (messages == null)
            {
                return(code.ToString());
            }
            else
            {
                var sb = new StringBuilder(code.ToString());
                foreach (var message in messages)
                {
                    sb.Append(";");
                    sb.Append(message);
                }
                return(sb.ToString());
            }
#endif
        }
Exemple #16
0
        /// <summary>
        /// 특정 파일에 기록할 로그를 작성한다. (주로 주문정보에 사용해야 함.)
        /// 예) D:\[로그폴더]\S20181231000111.txt 형식으로 기록함.
        /// </summary>
        /// <param name="fullFileName">전체파일이름 (경로 + 파일명)</param>
        /// <param name="owner">소유자(메서드 또는 클래스.메서드)</param>
        /// <param name="title">로그 제목</param>
        /// <param name="message"></param>
        /// <param name="logCode"></param>
        /// <param name="e"></param>
        public static void WriteLog(string fullFileName, string owner, string title, string message, LogCode logCode = LogCode.Information, Exception e = null)
        {
            var fullFilePath = Path.GetDirectoryName(fullFileName);

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

            var fullLog = string.Empty;

            if (e == null)
            {
                fullLog += $"{DateTime.Now.ToString("HH:mm:ss")} ({logCode.ToString()} [{owner}] [{title}] : {message})";
            }
            else
            {
                fullLog += $"{DateTime.Now.ToString("HH:mm:ss")} ({logCode.ToString()} [{owner}] [{title}] : {message})" + Environment.NewLine;
                fullLog += "Exception Message : " + e.Message + Environment.NewLine;
                fullLog += "Stack Trace : " + e.StackTrace;
            }

            var ext = Path.GetExtension(fullFileName);
            var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fullFileName);
            var lastExtIndex       = fullFileName.LastIndexOf(".", StringComparison.CurrentCulture);

            fullFileName = fullFileName.Substring(0, lastExtIndex) + DateTime.Now.ToString("yyyyMMdd") + ext;

            try
            {
                using (var sw = new StreamWriter(fullFileName, true, Encoding.UTF8, 4096))
                {
                    sw.WriteLine(fullLog);
                    sw.Close();
                    sw.Dispose();
                }
            }
            catch (Exception ex)
            {
                if (!EventLog.SourceExists(_source))
                {
                    EventLog.CreateEventSource(_source, _log);
                    EventLog.WriteEntry(_source, ex.Message, EventLogEntryType.Error, 234);
                }
                else
                {
                    EventLog.WriteEntry(_source, ex.Message, EventLogEntryType.Error, 234);
                }
            }
        }
 public void WriteEntry(string message, object error, LogCode code = LogCode.None)
 {
     Console.WriteLine($"message: {message}, error: {error}, code: {code}");
 }
Exemple #18
0
 public static void Out(string sender, string message, LogCode code = LogCode.Log)
 {
     Debug.WriteLine("[" + DateTime.Now + "]" + sender + "[" + code + "]: " + message);
 }
Exemple #19
0
 public static void Out(string sender,string message,LogCode code=LogCode.Log)
 {
     Console.WriteLine("[" +DateTime.Now + "]" +sender + "["+code+"]: " + message);
 }
Exemple #20
0
 public void Log(LogLevel level, LogCode code, params object[] args)
 {
     throw new NotImplementedException();
 }
Exemple #21
0
 public void Info(LogCode code, params string[] messages)
 {
     items.Add(new LogItem(LogType.Log, code, messages));
 }
Exemple #22
0
 public LogAttribute(LogCode logCode)
 {
     this.logCode = logCode;
 }
 private void SendLog(LogCode logCode, object addData)
 {
     log?.LogCallback(new LogData(logCode, addData));
 }
Exemple #24
0
 /// <inheritdoc />
 public void Info(LogCode code, params string[] messages)
 {
     Debug.Log(LogMessages.GetFullMessage(code, messages));
 }
Exemple #25
0
 public static void WriteLog(string strLog, LogCode logCode, string strFileName)
 {
     WriteLog(strLog, logCode, strFileName, strLogDir);
 }
Exemple #26
0
 public static void WriteLog(string strLog, LogCode logCode)
 {
     WriteLog(strLog, logCode, strLogFile);
 }
 public LogData(LogCode logCode, object addData)
 {
     this.logCode = logCode;
     this.addData = addData;
 }
 public LogItem(LogType type, LogCode code, params string[] messages)
 {
     this.type     = type;
     this.code     = code;
     this.messages = messages;
 }
 public LogData(LogCode logCode) : this(logCode, null)
 {
 }
Exemple #30
0
 public LogResult(LogCode _code, object _result, string _timestamp)
 {
     code      = _code;
     result    = _result;
     timestamp = _timestamp;
 }
Exemple #31
0
 public LogResult(LogCode _code, object _result, string _timestamp)
 {
     code = _code;
     result = _result;
     timestamp = _timestamp;
 }
 private void SendLog(LogCode logCode)
 {
     log?.LogCallback(new LogData(logCode));
 }
 public void WriteEntry(string message, EventLogEntryType error, LogCode errorCode = LogCode.None)
 {
     throw new NotImplementedException();
 }