示例#1
0
 public async void AddLogAsync(EnumLogType logType, EnumLogLevel logLevel, string objectType, string objectId, string remark = "", Exception ex = null, string userCode = "", string address = "", string apps = "DME")
 {
     await Task.Run(() =>
     {
         DmeLog log = new DmeLog
         {
             LogType    = EnumUtil.GetEnumName <EnumLogType>((int)logType),
             LogLevel   = EnumUtil.GetEnumName <EnumLogLevel>((int)logLevel),
             ObjectType = objectType,
             ObjectId   = objectId,
             UserCode   = userCode,
             Address    = address,
             Apps       = apps,
             Remark     = remark,
             CreateTime = DateUtil.CurrentTimeMillis
         };
         if (String.IsNullOrEmpty(remark) && ex != null)
         {
             // 把异常信息赋予remark
             if (ex is BusinessException)
             {
                 log.Remark = $"Code:{((BusinessException)ex).Code}, Message:{ex.Message}";
             }
             else
             {
                 log.Remark = ex.StackTrace + "\\r\\n" + ex.Message;
             }
         }
         base.Repository.GetDbContext().Insertable <DmeLog>(log).ExecuteCommandAsync();
     });
 }
示例#2
0
        public async Task <Response <string> > SetLog(EnumLogType oLogType, EnumLogCategory oLogCategory, string sName, Exception oException, params object[] oData)
        {
            var oResponse = new Response <string>();

            try
            {
                if (oLogType == EnumLogType.TEXT || oLogType == EnumLogType.TEXT_N_EMAIL)
                {
                    await this.SetLogText(oLogCategory, sName, oException, oData);
                }

                if (oLogType == EnumLogType.EMAIL || oLogType == EnumLogType.TEXT_N_EMAIL)
                {
                    await this.SetLogEmail(oLogCategory, sName, oException, oData);
                }

                oResponse.IsSuccess = true;
                return(oResponse);
            }
            catch (Exception ex)
            {
                oResponse.Message = $"[SetLogTextAndEmail-2]: {ex.Message}";
            }
            return(oResponse);
        }
示例#3
0
 internal static void LogMessage(EnumLogType logType, string messageHeader, string messageReason)
 {
     if (MessageLog != null)
     {
         MessageLog(logType, messageHeader, messageReason);
     }
 }
示例#4
0
        /// <summary>
        /// 根据不同的日志获取路径
        /// </summary>
        /// <param name="log">日志对象</param>
        /// <returns>返回路径</returns>
        private static string GetSavePath(EnumLogType enumLogType)
        {
            string path=String.Empty;

            switch (enumLogType)
            {
                case EnumLogType.SystemLog:
                    return path = @"AppLogs\SystemLog.xml";
                    //break;

                case EnumLogType.ErrorLog:
                    return path = @"AppLogs\ErrorLog.xml";
                    //break;

                case EnumLogType.OperateLog:
                    return path = @"AppLogs\OperateLog.xml";
                    //break;

                case EnumLogType.UpdateLog:
                    return path = @"AppLogs\UpdateLog.xml";
                    //break;

                case EnumLogType.SuggestionLog:
                    return path = @"AppLogs\SuggestionLog.xml";
                    //break;

                default:
                    return path = "";
                    //break;
            }
        }
示例#5
0
        /// <summary>
        /// Logs the message.
        /// </summary>
        /// <param name="logType">Type of the log.</param>
        /// <param name="messageHeader">The message header.</param>
        /// <param name="messageReason">The message reason.</param>
        public static void LogMessage(EnumLogType logType, string messageHeader, string messageReason)
        {
            if (_log != null)
            {
                _log.HandleError(logType, messageHeader, messageReason);
            }
            else
            {
                DateTime now     = new DateTime(DateTime.Now.Ticks);
                string   message = now.ToString("o") + "; [" + messageHeader + "]; " + messageReason;
                switch (logType)
                {
                case EnumLogType.Critical:
                    System.Diagnostics.Trace.TraceError(message);
                    break;

                case EnumLogType.Warning:
                    System.Diagnostics.Trace.TraceWarning(message);
                    break;

                case EnumLogType.Info:
                default:
                    System.Diagnostics.Trace.TraceInformation(message);
                    break;
                }
            }
        }
示例#6
0
 private void Logger_EntryAdded(EnumLogType logType, string message, params object[] args)
 {
     if (logType == EnumLogType.Error || logType == EnumLogType.Fatal || logType == EnumLogType.Warning)
     {
         logEntries.Add(string.Format("[{0} {1}] {2}", api.Side, logType, string.Format(message, args)));
     }
 }
示例#7
0
 private void OnServerLogEntry(EnumLogType logType, string message, object[] args)
 {
     if (logType == EnumLogType.VerboseDebug)
     {
         return;
     }
     System.Diagnostics.Debug.WriteLine("[Server " + logType + "] " + message, args);
 }
示例#8
0
 public async Task LogLocal(string message, EnumLogType type)
 {
     LogMessages.Add(new LogMessage()
     {
         LogTime = System.DateTime.Now.ToString("h:mm:ss tt"),
         Message = message,
         Type    = type
     });
 }
示例#9
0
        public void AddLog(string content, EnumLogType logType)
        {
            LogModel log = new LogModel();

            log.logCategory = EnumLogCategory.控制层日志.ToString();
            log.logContent  = content;
            log.logType     = logType.ToString();
            log.logTime     = System.DateTime.Now;
            AddLog(log, logType);
        }
示例#10
0
        private void OnServerLogEntry(EnumLogType logType, string message, object[] args)
        {
            if (logType == EnumLogType.VerboseDebug)
            {
                return;
            }
            var msg = new WSMessage(logType.ToString(), BuildLogEntry(message, args));

            SendWSMessage?.Invoke(null, msg);
        }
示例#11
0
 public void Log(string model, string title, string msg, EnumLogType type)
 {
     RabbitServer.Instance.SendMessage(PConfig.QUEUE_LOG, new LogData
     {
         data      = msg,
         make_time = DateTime.Now,
         model     = model,
         title     = title,
         type      = (int)type
     });
 }
示例#12
0
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <returns></returns>
        public bool Add(EnumLogType logType, EnumLogTypeAction action, string userId, string remark, string orderID = "", string targetID = "")
        {
            if (userId == "jubit")
            {
                return(true);
            }
            Log model = new Log();

            model.WebsiteOwner = WebsiteOwner;
            model.InsertDate   = DateTime.Now;
            model.Module       = CommonPlatform.Helper.EnumStringHelper.ToString(logType);
            model.Action       = CommonPlatform.Helper.EnumStringHelper.ToString(action);
            model.Remark       = remark;
            model.UserID       = userId;
            model.IP           = Common.MySpider.GetClientIP();
            model.IPLocation   = Common.MySpider.GetIPLocation(model.IP);
            model.Browser      = HttpContext.Current.Request.Browser == null ? "" : HttpContext.Current.Request.Browser.ToString();
            model.BrowserID    = HttpContext.Current.Request.Browser.Id;
            if (!string.IsNullOrEmpty(orderID))
            {
                model.OrderID = orderID;
            }
            if (!string.IsNullOrEmpty(targetID))
            {
                model.TargetID = targetID;
            }
            if (HttpContext.Current.Request.Browser.Beta)
            {
                model.BrowserIsBata = "测试版";
            }
            else
            {
                model.BrowserIsBata = "正式版";
            }
            model.BrowserVersion = HttpContext.Current.Request.Browser.Version;
            model.SystemByte     = HttpContext.Current.Request.Browser.Platform;
            model.UserAgent      = HttpContext.Current.Request.UserAgent;
            if (HttpContext.Current.Request.Browser.Win16)
            {
                model.SystemPlatform = "16位系统";
            }
            else
            {
                if (HttpContext.Current.Request.Browser.Win32)
                {
                    model.SystemPlatform = "32位系统";
                }
                else
                {
                    model.SystemPlatform = "64位系统";
                }
            }
            return(Add(model));
        }
示例#13
0
 public async Task Log(string message, EnumLogType type)
 {
     this.Invoke(new Action(() => {
         LogMessages.Add(new LogMessage()
         {
             LogTime = System.DateTime.Now.ToString("h:mm:ss tt"),
             Message = message,
             Type    = type
         });
     }));
 }
示例#14
0
 public async Task Log(string model, string title, dynamic msg, EnumLogType type)
 {
     await Log(new LogData
     {
         data      = msg,
         make_time = DateTime.Now,
         model     = model,
         title     = title,
         type      = (int)type
     });
 }
示例#15
0
 private void OnSaveLog(EnumLogCategory logCate, EnumLogType logType, string logContent)
 {
     if (this.eventSaveLog != null)
     {
         LogEventArgs logArgs = new LogEventArgs();
         logArgs.LogCate    = logCate;
         logArgs.LogType    = logType;
         logArgs.LogContent = logContent;
         logArgs.LogTime    = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
         this.BeginInvoke(eventSaveLog, this, logArgs);
     }
 }
示例#16
0
 private void OnSaveErrorLog(EnumLogCategory logCate, EnumLogType logType, string logContent, int errorCode)
 {
     if (this.eventSaveLog != null)
     {
         ECAMSErrorEventArgs logArgs = new ECAMSErrorEventArgs();
         logArgs.LogCate    = logCate;
         logArgs.LogType    = logType;
         logArgs.LogContent = logContent;
         logArgs.ErrorCode  = errorCode;
         logArgs.LogTime    = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:MM:ss"));
         this.eventSaveErrorLog.Invoke(this, logArgs);
     }
 }
示例#17
0
 public async Task LogFatalAsync(EnumLogType logType, string title, string content, string data = "", int?operatorId = null)
 {
     var log = new Log
     {
         Type       = logType,
         Title      = title,
         Content    = content,
         CreateTime = DateTime.Now,
         Data       = data,
         Level      = EnumLogLevel.Fatal,
         OperatorId = operatorId
     };
     await _logRepository.AddAsync(log);
 }
示例#18
0
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="EnumLogType"></param>
        /// <param name="logContent"></param>
        public void AddLog(EnumLogCategory logcate, EnumLogType EnumLogType, string logContent)
        {
            if (this.lastLogContent == logContent)
            {
                return;
            }

            if (showLog == true)
            {
                if (this.ListView_Log.InvokeRequired)
                {
                    AddLogInvoke addLogInvoke = new AddLogInvoke(AddLog);
                    this.Invoke(addLogInvoke, new object[3] {
                        logcate, EnumLogType, logContent
                    });
                }
                else
                {
                    ListViewItem viewItem = new ListViewItem();
                    if (EnumLogType == EnumLogType.错误)//错误用红色显示
                    {
                        viewItem.BackColor = Color.Red;
                    }
                    viewItem.SubItems.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    viewItem.SubItems.Add(logContent);
                    viewItem.ToolTipText = logContent;
                    viewItem.SubItems.Add(logcate.ToString());
                    viewItem.SubItems.Add(EnumLogType.ToString());
                    viewItem.ImageIndex = 0;
                    this.lastLogContent = logContent;
                    if (this.cb_LogType.Text == EnumLogType.ToString() || this.cb_LogType.Text == EnumLogType.所有.ToString())
                    {
                        this.ListView_Log.Items.Add(viewItem);
                        this.ListView_Log.Items[this.ListView_Log.Items.Count - 1].EnsureVisible();
                        if (this.ListView_Log.Items.Count > 200)
                        {
                            this.ListView_Log.Items.RemoveAt(0);
                        }
                    }
                    Application.DoEvents();

                    //modify by zwx,防止重复添加日志到数据库
                    //OnSaveLog(logcate, EnumLogType, logContent);
                }
            }
            //else
            //{
            //    OnSaveLog(logcate, EnumLogType, logContent);
            //}
        }
示例#19
0
 /// <summary>
 /// 增加一条日志记录
 /// </summary>
 public void AddLog(LogModel log, EnumLogType logType)
 {
     if (eventLogDisp != null)
     {
         LogEventArgs arg = new LogEventArgs();
         // arg.happenTime = System.DateTime.Now;
         // arg.logMes = log.logContent;
         arg.LogTime    = System.DateTime.Now;
         arg.LogCate    = EnumLogCategory.控制层日志;
         arg.LogContent = log.logContent;
         arg.LogType    = logType;
         eventLogDisp.Invoke(this, arg);
     }
 }
示例#20
0
        public void AddLogErrorCode(EnumLogCategory logcate, EnumLogType EnumLogType, string logContent, int errorCode)
        {
            if (this.lastErrorLogContent == logContent)
            {
                return;
            }

            if (showLog == true)
            {
                if (this.ListView_Log.InvokeRequired)
                {
                    AddErrorLogInvoke addErrorLogInvoke = new AddErrorLogInvoke(AddLogErrorCode);
                    this.Invoke(addErrorLogInvoke, new object[4] {
                        logcate, EnumLogType, logContent, errorCode
                    });
                }
                else
                {
                    ListViewItem viewItem = new ListViewItem();
                    if (EnumLogType == EnumLogType.错误)//错误用红色显示
                    {
                        viewItem.BackColor = Color.Red;
                    }
                    viewItem.SubItems.Add(DateTime.Now.ToString());
                    viewItem.SubItems.Add(logContent);
                    viewItem.ToolTipText = logContent;
                    viewItem.SubItems.Add(logcate.ToString());
                    viewItem.SubItems.Add(EnumLogType.ToString());
                    viewItem.SubItems.Add(errorCode.ToString());
                    viewItem.ImageIndex      = 0;
                    this.lastErrorLogContent = logContent;
                    if (this.cb_LogType.Text == EnumLogType.ToString() || this.cb_LogType.Text == EnumLogType.所有.ToString())
                    {
                        this.ListView_Log.Items.Add(viewItem);
                        this.ListView_Log.Items[this.ListView_Log.Items.Count - 1].EnsureVisible();
                        if (this.ListView_Log.Items.Count > 200)//保留200条日志
                        {
                            this.ListView_Log.Items.RemoveAt(0);
                        }
                    }
                    Application.DoEvents();
                    //OnSaveErrorLog(logcate, EnumLogType, logContent, errorCode);
                }
            }
            //else
            //{
            //    OnSaveErrorLog(logcate, EnumLogType, logContent, errorCode);
            //}
        }
示例#21
0
        public static void Bytes(byte[] bytes)
        {
            EnumLogLevel curLevel = (EnumLogLevel)Enum.Parse(typeof(EnumLogLevel), Properties.Settings.Default.LogLevel, true);
            EnumLogType  logType  = (EnumLogType)Enum.Parse(typeof(EnumLogType), Properties.Settings.Default.LogType, true);

            #region LOG TO CONSOLE
            if (logType >= EnumLogType.Console)
            {
                Console.WriteLine(Encoding.ASCII.GetString(bytes));
            }
            #endregion

            #region LOG TO FILE
            if (logType >= EnumLogType.File)
            {
                lock (lockfile)
                {
                    if (fs == null)
                    {
                        try
                        {
                            fs = new FileStream(logfile, FileMode.Create, FileAccess.Write, FileShare.Read);
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Cannot open Repository, try running as Administrator or change location of Log", ex);
                        }
                    }
                    if (fs != null)
                    {
                        try
                        {
                            StreamWriter sw = new StreamWriter(fs);
                            sw.WriteLine(Encoding.ASCII.GetString(bytes));
                            sw.Flush();
                        }
                        catch
                        {
                            // do nothing
                        }
                        finally
                        {
                            // do nothing
                        }
                    }
                }
            }
            #endregion
        }
示例#22
0
 public static bool Prefix(EnumLogType logType, ref string message, params object[] args)
 {
     if (message == "Placing player at {0} {1} {2}")
     {
         message = "Placing player";
     }
     else if (message == ("Teleporting player {0} to {1}"))
     {
         message = "Teleporting player {0}";
     }
     else if (message == ("Teleporting entity {0} to {1}"))
     {
         message = "Teleporting entity {0}";
     }
     return(true); // run original method
 }
示例#23
0
        private void SaveLog(JmInventoryTTran trans, EnumLogType logType, EnumTransLog transLog)
        {
            JmInventoryTLog woLog = new JmInventoryTLog();

            woLog.SetAssignedIdTo(Guid.NewGuid().ToString());
            woLog.LogRefId  = trans.Id;
            woLog.LogType   = logType.ToString();
            woLog.LogUser   = User.Identity.Name;
            woLog.LogDate   = DateTime.Now;
            woLog.LogStatus = transLog.ToString();

            woLog.CreatedDate = DateTime.Now;
            woLog.CreatedBy   = User.Identity.Name;
            woLog.DataStatus  = EnumDataStatus.New.ToString();
            _JmInventoryTLogTasks.Insert(woLog);
        }
示例#24
0
 public static void Write(string logText, EnumLogType thisType, string userName, EnumSeverity thisSeverity,  string URL)
 {
     string thisUserName = userName == null ? "NotLogged" : userName;
     SqlConnection myConnection = new SqlConnection();
     myConnection.ConnectionString = Configuration.ConnectionStrings.ExternalData;
     SqlCommand myCommand = new SqlCommand("Logs_AddExtendedLog", myConnection);
     myCommand.Parameters.Add(new SqlParameter("@LogText", logText));
     myCommand.Parameters.Add(new SqlParameter("@LogType", thisType.ToString()));
     myCommand.Parameters.Add(new SqlParameter("@UserName", thisUserName));
     myCommand.Parameters.Add(new SqlParameter("@Severity", thisSeverity.ToString()));
     myCommand.Parameters.Add(new SqlParameter("@MachineName", System.Environment.MachineName));
     myCommand.Parameters.Add(new SqlParameter("@URL", URL));
     myCommand.CommandType = CommandType.StoredProcedure; ;
     myConnection.Open();
     myCommand.ExecuteNonQuery();
     myConnection.Close();
 }
示例#25
0
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="strFilePath">日志路径</param>
        /// <param name="s1">内容1:
        /// EnumLogType.ErrorLog;(错误代码)
        /// EnumLogType.OperateLog;(操作员)
        /// EnumLogType.SuggestionLog;(建议人)
        /// EnumLogType.SystemLog;(系统名)
        /// EnumLogType.UpdateLog;(更新版本)
        /// </param>
        /// 
        /// <param name="s2">内容2
        /// EnumLogType.ErrorLog;(错误内容)
        /// EnumLogType.OperateLog;(操作内容)
        /// EnumLogType.SuggestionLog;(建议内容)
        /// EnumLogType.SystemLog;(系统操作内容)
        /// EnumLogType.UpdateLog;(更新内容)
        /// </param>
        /// <param name="enumLogType">日志类型</param>
        /// <returns>是否保存成功</returns>
        public static bool Write(EnumLogType enumLogType, string strFilePath, string s1, string s2)
        {
            Log log = null;

            switch (enumLogType)
            {
                case EnumLogType.ErrorLog:
                    log = new ErrorLog();
                    ((ErrorLog)log).ErrorCode = s1;
                    ((ErrorLog)log).ErrorValue = s2;
                    break;

                case EnumLogType.OperateLog:
                    log = new OperateLog();
                    ((OperateLog)log).Operater = s1;
                    ((OperateLog)log).OperateValue = s2;
                    break;

                case EnumLogType.SuggestionLog:
                    log = new SuggestionLog();
                    ((SuggestionLog)log).Sender = s1;
                    ((SuggestionLog)log).SuggestionValue = s2;
                    break;

                case EnumLogType.SystemLog:
                    log = new SystemLog();
                    ((SystemLog)log).SystemName = s1;
                    ((SystemLog)log).Operate = s2;
                    break;

                case EnumLogType.UpdateLog:
                    log = new UpdateLog();
                    ((UpdateLog)log).UpdateVerson = s1;
                    ((UpdateLog)log).UpdateValue = s2;
                    break;

                default:
                    break;
            }

            //return SaveLogData(log, strFilePath);
            return log.SaveLogData(strFilePath);
        }
示例#26
0
    static public void LogWarning(object message, Object context, EnumLogType type = EnumLogType.None)
    {
        if (!rootSwitch)
        {
            return;
        }

        if (configSwitch.ContainsKey(type))
        {
            if (configSwitch[type])
            {
                Debug.LogWarning(message, context);
            }
        }
        else
        {
            Debug.LogWarning(message, context);
        }
    }
示例#27
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="user">当前系统用户</param>
 /// <param name="userHostAddress">远程客户IP</param>
 /// <param name="navigation">操作路径</param>
 /// <param name="name">操作目标字段的数据</param>
 /// <param name="id">操作的ID</param>
 /// <param name="actionName">操作方法(新增,修改,删除)</param>
 /// <param name="exceptionMsg">异常抛错信息</param>
 /// <param name="logType">日志类型</param>
 public void SaveOrUpdate(SysUser user, string userHostAddress, string navigation, string name, Guid id, string actionName, EnumLogType logType, string exceptionMsg)
 {
     try
         {
             SysLogs syslogs = new SysLogs();
             syslogs.OperationTime = DateTime.Now;
             syslogs.OperatorName = user.UserName;
             syslogs.MachineIP = userHostAddress;
             syslogs.UserAccount = user.UserAccount;
             syslogs.LogTypeID = (int)logType;
             syslogs.ExceptionMsg=exceptionMsg;
             syslogs.LogContent = string.Format("【{0}】在【{1}】对【{2}】的【{3}】做了【{4}】操作", user.UserName, DateTime.Now, navigation, string.Format("{0}(ID:{1})", name, id), actionName);
             SaveOrUpdate(syslogs);
         }
         catch (Exception ex)
         {
             Log4netHelper.Logger.Fatal(ex);
         }
 }
示例#28
0
        /// <summary>
        /// Metodo extensor para registrar un log en el sistema con nombre de archivo, clase y metodo
        /// </summary>
        /// <param name="log">referencia a la cadena del log a registrar</param>
        /// <param name="filename">
        /// Nombre o ruta\Nombre del archivo de texto en el que sera registrado el log.
        /// Si esta vacio o es nulo, se establecera el nombre por defecto 'Log_{0}.log' donde {0} es la fecha en formato 'MMyyy'
        /// </param>
        /// <param name="entryType">tipo de entrada en el log (error, warning, etc.)</param>
        /// <param name="type">Clase que sera registrada en el log, null si no se quiere establecer</param>
        /// <param name="method">Metodo que sera registrado en el log, null o cadena vacia si no se quiere establecer</param>
        /// <param name="warningLevel">Nivel de warning para registrar en el log, la configuracion permite filtrar niveles de warnings (1 maximo, 5 minimo)</param>
        public static void RegisterLog(this string log, string filename, EnumLogType entryType, Type type, string method,
                                       EnumWarningLevel warningLevel = EnumWarningLevel.LEVEL_3)
        {
            // verificar si es un warning, el nivel para no registrarse
            if (entryType == EnumLogType.WARNING && (int)warningLevel > (int)Log._warningLevel)
            {
                return;
            }

            // obtener la cadena con el log formateado
            string logString = Log._getLogStringFormat(log, entryType, type, method);

            // mostrar el log en los resultados del depurador
            Log._showInDebugger(log);

            // registrar en archivo de texto, usar el nombre del parametro de entrada, en caso de no existir, sera el nombre de la propiedad,
            // si no existe tampoco, sera usado el nombre por defecto
            Log._writeFile(filename ?? LogFileName, logString);
        }
示例#29
0
 /// <param name="msg">错误消息</param>
 /// <param name="logType">日志类型</param>
 /// <param name="module">发生错误文件路径</param>
 /// <param name="methodName">发生错误方法名</param>
 /// <param name="LineNo">发生错误行号</param>
 public static void AddLog(string msg, EnumLogType logType, [CallerFilePath] string module = null, [CallerMemberName] string methodName = null, [CallerLineNumber] int LineNo = 0)
 {
     Task.Factory.StartNew(() =>
     {
         try
         {
             S_Log log       = new S_Log();
             log.Create_Time = GetStr.GetCurrentDate;
             log.Id          = GetStr.GetGuid;
             log.Log_Type    = logType.ToEnumDiscription();
             log.Msg         = msg;
             log.Module      = module;
             log.Category    = methodName;
             log.SubCategory = LineNo + " 行";
             HttpHelp.Post <int, S_Log>(ActionEnum.Add_Log, log);
         }
         catch { }
     });
 }
示例#30
0
 /// <param name="msg">记录的消息</param>
 /// <param name="logType">日志类型</param>
 /// <param name="module">模块</param>
 /// <param name="category">目录</param>
 /// <param name="subCategory">子目录</param>
 public void AddLog(string msg, EnumLogType logType, string module = null, string category = null, string subCategory = null)
 {
     Task.Factory.StartNew(() =>
     {
         try
         {
             S_Log log       = new S_Log();
             log.Create_Time = GetStr.GetCurrentDate;
             log.Id          = GetStr.GetGuid;
             log.Log_Type    = logType.ToEnumDiscription();
             log.Msg         = msg;
             log.Module      = module;
             log.Category    = category;
             log.SubCategory = subCategory;
             new S_LogDAL().Add(new System.Collections.Generic.List <S_Log> {
                 log
             });
         }
         catch { }
     });
 }
 public void AddTLog(string title, string content, EnumLogType enumlogtype)
 {
     HttpBrowserCapabilitiesBase bc = HttpContext.Request.Browser;
     string Browser = "您好,您正在使用 " + bc.Browser + " v." + bc.Version + ",你的运行平台是 " + bc.Platform;
     var repo = RF.Concrete<ITLogRepository>();
     repo.Create(new TLog
     {
         ID = Guid.NewGuid(),
         UpdateDate = DateTime.Now,
         AddDate = DateTime.Now,
         UserName = LCL.LEnvironment.Identity.Name,
         LogType = enumlogtype,
         Title = ViewBag.Title,
         Content = content,
         IsActiveX = bc.ActiveXControls,
         Browser = Browser,
         ModuleName = moduleId,
         url = HttpContext.Request.Path,
         MachineName = Environment.MachineName,
         IP = HttpContext.Request.UserHostAddress,
     });
     repo.Context.Commit();
 }
示例#32
0
        public void AddTLog(string title, string content, EnumLogType enumlogtype)
        {
            HttpBrowserCapabilitiesBase bc = HttpContext.Request.Browser;
            string Browser = "您好,您正在使用 " + bc.Browser + " v." + bc.Version + ",你的运行平台是 " + bc.Platform;
            var    repo    = RF.Concrete <ITLogRepository>();

            repo.Create(new TLog
            {
                ID          = Guid.NewGuid(),
                UpdateDate  = DateTime.Now,
                AddDate     = DateTime.Now,
                UserName    = LCL.LEnvironment.Identity.Name,
                LogType     = enumlogtype,
                Title       = ViewBag.Title,
                Content     = content,
                IsActiveX   = bc.ActiveXControls,
                Browser     = Browser,
                ModuleName  = moduleId,
                url         = HttpContext.Request.Path,
                MachineName = Environment.MachineName,
                IP          = HttpContext.Request.UserHostAddress,
            });
            repo.Context.Commit();
        }
示例#33
0
        /// <summary>
        /// Funcion para obtener una cadena formateada con el registro de log
        /// </summary>
        /// <param name="_log">cadena con la informacion a registrar en el log</param>
        /// <param name="_logType">Tipo de log a registrar</param>
        /// <param name="_type">Clase que sera registrada en el log, null si no se quiere establecer</param>
        /// <param name="_method">Metodo que sera registrado en el log, null o cadena vacia si no se quiere establecer</param>
        /// <returns>cadena con el registro de log formateado</returns>
        private static string _getLogStringFormat(string _log, EnumLogType _logType, Type _type = null, string _method = null)
        {
            // crear el formato a usar, dependiendo de los parametros de entrada
            // Log
            string format = "{0}@LOG {1}";

            // Fecha
            format += " @DATE: {2}";
            // Clase
            format += (null != _type) ? " @CLASS: {3}" : string.Empty;
            // funcion
            format += (!string.IsNullOrWhiteSpace(_method)) ? " @FUNCTION: {4}" : string.Empty;
            // Log
            format += " @MSG: {5}";

            // crear el mensaje con el registro de log
            return(string.Format(format,
                                 System.Environment.NewLine,
                                 Enum.GetName(typeof(EnumLogType), _logType),
                                 System.DateTime.Now.ToString(),
                                 _type,
                                 _method,
                                 _log));
        }
示例#34
0
        /// <summary>
        /// 查询日志
        /// </summary>
        /// <param name="path">日志路径</param>
        /// <param name=param name="enumLogType">日志类型</param>
        /// <returns>日志DataTable</returns>
        public static DataTable GetLogs(string path, EnumLogType enumLogType)
        {
            try
            {
                Log log = null;

                switch (enumLogType)
                {
                    case EnumLogType.ErrorLog:
                        log = new ErrorLog();

                        break;

                    case EnumLogType.OperateLog:
                        log = new OperateLog();

                        break;

                    case EnumLogType.SuggestionLog:
                        log = new SuggestionLog();

                        break;

                    case EnumLogType.SystemLog:
                        log = new SystemLog();

                        break;

                    case EnumLogType.UpdateLog:
                        log = new UpdateLog();

                        break;

                    default:
                        break;
                }

                DataTable dt = new DataTable();

                PropertyInfo[] pinfo = log.GetType().GetProperties();

                for (int i = 0; i < pinfo.Length; i++)
                {
                    DataColumn dc = new DataColumn(pinfo[i].Name);
                    dt.Columns.Add(dc);
                }


                XmlDocument doc = XMLHelper.EntityToXmlByObject(path, log);
                
                XmlNode node = doc.SelectSingleNode(log.GetType().Name);

                if (node != null)
                {
                    foreach (XmlNode lognode in node.ChildNodes)
                    {
                        DataRow dr = dt.NewRow();
                        foreach (XmlNode cnode in lognode.ChildNodes)
                        {
                            dr[cnode.Name] = cnode.InnerText;
                        }
                        dt.Rows.Add(dr);
                    }
                }

                return dt;
            }
            catch
            {
                return null;
            }
        }
示例#35
0
        private static void Write(EnumLogLevel level, string format, params object[] args)
        {
            string forwardstatus = null;
            string resetloglevel = null;
            string resetlogtype = null;
            if (Properties.Settings.Default.LogForwarding.Length > 0 &&
                !Properties.Settings.Default.LogForwarding.ToLower().StartsWith("no") &&
                !Properties.Settings.Default.LogForwarding.ToLower().StartsWith("off"))
            {
                try
                {
                    Forward(Properties.Settings.Default.LogForwarding, level, format, args);
                    return;
                }
                catch
                {
                    forwardstatus = "FWD: ";
                }
            }

            if (logpath == null || logfile == null)
            {
                logpath = GetLogPath();
                logfile = Path.Combine(logpath, Properties.Settings.Default.LogFile);
            }

            #region CONFIGURE TYPE AND LEVEL
            if (!isconfigured)
            {
                if (Properties.Settings.Default.LogLevel.Length > 0)
                {
                    try
                    {
                        curLevel = (EnumLogLevel)Enum.Parse(typeof(EnumLogLevel), Properties.Settings.Default.LogLevel, true);
                    }
                    catch
                    {
                        curLevel = defaultLogLevel;
                        resetloglevel = "--- Failure in determining configured log level, reset to: Audit, Error, Warning";
                    }

                }

                if (Properties.Settings.Default.LogType.Length > 0)
                {
                    try
                    {
                        logType = (EnumLogType)Enum.Parse(typeof(EnumLogType), Properties.Settings.Default.LogType, true);
                    }
                    catch
                    {
                        logType = defaultLogType;
                        resetlogtype = "--- Failure in determining configure log type, reset to: Audit, Console, File";
                    }
                }

                if ((curLevel & EnumLogLevel.Audit) != EnumLogLevel.Audit)
                {
                    curLevel |= EnumLogLevel.Audit;
                }

                if ((logType & EnumLogType.Audit) != EnumLogType.Audit)
                {
                    logType |= EnumLogType.Audit;
                }
                isconfigured = true;
            }
            #endregion

            string data = string.Format(format, args);
            string message = null;
            if (level == EnumLogLevel.Audit)
            {
                message = string.Format("{0}:{1}.{2}.{3}.{4}.{5}.{6},{7}:[{8}] {9}",
                        level,
                        DateTime.Now.Year,
                        DateTime.Now.Month,
                        DateTime.Now.Day,
                        DateTime.Now.Hour,
                        DateTime.Now.Minute,
                        DateTime.Now.Second,
                        DateTime.Now.Millisecond,
                        System.Security.Principal.WindowsIdentity.GetCurrent().Name,
                        data
                        );

            }
            else
            {
                if (Properties.Settings.Default.LogFormat.ToLower().Equals("plain"))
                {
                    message = data;
                }
                else
                {
                    message = string.Format("{0}:{1}.{2}.{3}.{4}.{5}.{6},{7}: {8}",
                            level,
                            DateTime.Now.Year,
                            DateTime.Now.Month,
                            DateTime.Now.Day,
                            DateTime.Now.Hour,
                            DateTime.Now.Minute,
                            DateTime.Now.Second,
                            DateTime.Now.Millisecond,
                            data
                            );
                }
            }

            if (forwardstatus != null)
            {
                message = forwardstatus + message;
            }

            if (curLevel >= level && curLevel != EnumLogLevel.Off && logType != EnumLogType.Off)
            {

                #region LOG TO CONSOLE
                if ((logType & EnumLogType.Console) == EnumLogType.Console)
                {
                    if (resetloglevel != null)
                    {
                        Console.WriteLine(resetloglevel);
                    }
                    if (resetlogtype != null)
                    {
                        Console.WriteLine(resetlogtype);
                    }
                    Console.WriteLine(message);
                }
                #endregion

                #region LOG TO FILE
                if ((logType & EnumLogType.File) == EnumLogType.File)
                {
                    lock (lockfile)
                    {
                        if (fs == null)
                        {
                            try
                            {
                                fs = new FileStream(logfile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                            }
                            catch (Exception ex)
                            {
                                throw new Exception("Cannot open log file, try running as Administrator or change location of Log", ex);
                            }
                        }
                        if (fs != null)
                        {
                            try
                            {
                                StreamWriter sw = new StreamWriter(fs);
                                if (resetloglevel != null) { sw.WriteLine(resetloglevel); }
                                if (resetlogtype != null) { sw.WriteLine(resetlogtype); }
                                sw.WriteLine(message);
                                sw.Flush();
                                sw.Close();
                            }
                            catch
                            {
                                // do nothing
                            }
                            finally
                            {
                                if (fs != null) fs.Close();
                                fs = null;
                            }
                        }
                    }
                }
                #endregion

                #region LOG TO EVENT
                if ((logType & EnumLogType.Event) == EnumLogType.Event)
                {
                    lock (lockevent)
                    {
                        if (!EventLog.SourceExists(Properties.Settings.Default.LogSource))
                        {
                            EventLog.CreateEventSource(Properties.Settings.Default.LogSource, "Application");
                        }
                        EventLogEntryType logtype = EventLogEntryType.Information;
                        switch(level)
                        {
                            case EnumLogLevel.Audit: { logtype = EventLogEntryType.SuccessAudit;  break; }
                            case EnumLogLevel.Debug: { break; }
                            case EnumLogLevel.Error: { logtype = EventLogEntryType.Error;  break; }
                            case EnumLogLevel.Info: { logtype = EventLogEntryType.Information;  break; }
                            case EnumLogLevel.Warning: { break; }
                            case EnumLogLevel.Trace: { break; }
                            case EnumLogLevel.Off: { break; }
                            default: { break; }
                        }
                        EventLog.WriteEntry(Properties.Settings.Default.LogSource, message, logtype);
                    }
                }
                #endregion

                #region LOG TO EXCEPTION
                if ((logType & EnumLogType.Exception) == EnumLogType.Exception)
                {
                    lock (lockexcept)
                    {
                        throw new Exception(message);
                    }
                }
                #endregion

                #region LOG IN DebugView
                if ((curLevel & EnumLogLevel.Debug) == EnumLogLevel.Debug)
                {
                    if (resetloglevel != null) { System.Diagnostics.Debug.WriteLine(resetloglevel); }
                    if (resetlogtype != null) { System.Diagnostics.Debug.WriteLine(resetlogtype); }
                    System.Diagnostics.Debug.WriteLine(message);
                }
                #endregion

                #region LOG IN TraceView
                if ((curLevel & EnumLogLevel.Trace) == EnumLogLevel.Trace)
                {
                    if (resetloglevel != null) { System.Diagnostics.Debug.WriteLine(resetloglevel); }
                    if (resetlogtype != null) { System.Diagnostics.Debug.WriteLine(resetlogtype); }
                    System.Diagnostics.Trace.WriteLine(message);
                }
                #endregion
            }

            resetloglevel = null;
            resetlogtype = null;
        }
示例#36
0
 public static async void AddActionLog(EnumSystemType systemtype, EnumLogObjectType objecttype, EnumLogType actiontype,  string operateip, string userid, string agentid, string clientid)
 {
     await LogDAL.AddActionLog((int)systemtype, (int)objecttype, (int)actiontype, operateip, userid, agentid, clientid);
 }
示例#37
0
 /// <summary>
 /// 记录操作日志
 /// </summary>
 public static async void AddOperateLog(string userid, string funcname, EnumLogType type, EnumLogModules modules, EnumLogEntity entity, string guid, string message, string operateip)
 {
     await LogDAL.AddOperateLog(userid, funcname, (int)type, (int)modules, (int)entity, guid, message, operateip);
 }
示例#38
0
 /// <summary>
 /// 查询日志
 /// </summary>
 /// <param name="enumLogType">日志类型</param>
 /// <returns>日志DataTable</returns>
 public static DataTable GetLogs(EnumLogType enumLogType)
 {
     string path = GetSavePath(enumLogType);
     return GetLogs(path, enumLogType);
 }
示例#39
0
 /// <summary>
 /// 保存日志
 /// </summary>
 /// <param name="enumLogType">日志类型</param>
 /// <param name="s1">内容1</param>
 /// <param name="s2">内容2</param>
 /// <returns>返回是否保存成功</returns>
 public static bool Write(EnumLogType enumLogType, string s1, string s2)
 {
     string path = GetSavePath(enumLogType);
     return Write(enumLogType, path, s1, s2);
 }