Exemple #1
0
        /// <summary>
        /// 获取日志
        /// </summary>
        /// <returns></returns>
        public static List<LogEntity> GetLogs(string guid, EnumLogObjectType type, int pageSize, int pageIndex, ref int totalCount, ref int pageCount, string agentid)
        {
            string tablename = "";
            switch (type)
            {
                case EnumLogObjectType.Customer:
                    tablename = "CustomerLog";
                    break;
                case EnumLogObjectType.Orders:
                    tablename = "OrdersLog";
                    break;
            }

            DataTable dt = CommonBusiness.GetPagerData(tablename, "*", "LogGUID='" + guid + "'", "AutoID", pageSize, pageIndex, out totalCount, out pageCount);

            List<LogEntity> list = new List<LogEntity>();
            foreach (DataRow dr in dt.Rows)
            {
                LogEntity model = new LogEntity();
                model.FillData(dr);
                model.CreateUser = OrganizationBusiness.GetUserByUserID(model.CreateUserID, model.AgentID);

                list.Add(model);
            }
            return list;
        }
 public override void Append(LogEntity entity)
 {
     lock (this._lock)
     {
         base.Append(entity);
     }
 }
 public bool Matches(LogEntity log)
 {
     foreach (LogEntityMatcher matcher in this._matchers)
     {
         if (matcher.Matches(log)) return true;
     }
     return false;
 }
Exemple #4
0
 public void Save(LogEntity entToSave)
 {
     using (IUnitOfWork uow = _UnitFactory.GetUnit(this))
     {
         uow.BeginTransaction();
         uow.SaveOrUpdate(entToSave);
         uow.Commit();
     }
 }
 protected override void Append(LogEntity entity, string formatted)
 {
     try
     {
         this._writer.Write(formatted);
     }
     catch
     {
         // do nothing
     }
 }
        public void LogEntityConstructorTest()
        {
            string message = string.Empty; // TODO: Initialize to an appropriate value
            string category = string.Empty; // TODO: Initialize to an appropriate value
            string roleInstanceId = string.Empty; // TODO: Initialize to an appropriate value
            string deploymentId = string.Empty; // TODO: Initialize to an appropriate value
            string tenantId = string.Empty; // TODO: Initialize to an appropriate value

            roleInstanceId = "String1";
            category = "String1";
            message = "String1";
            tenantId = "ECC849C3-7ECD-45BA-BBAF-8DC4F95FA4A8";
            LogEntity target = new LogEntity(message, category, roleInstanceId, deploymentId, tenantId);
               // Assert.Inconclusive("TODO: Implement code to verify target");
        }
        void wc_UploadValuesCompleted(object sender, UploadValuesCompletedEventArgs e)
        {
            Operator user = OperatorProvider.Provider.Current();

            string fileName = "推送当前用户到培训平台,建立相关培训及考试任务_" + DateTime.Now.ToString("yyyyMMdd") + ".log";

            //将同步结果写入日志文件
            try
            {
                int       _actionType = 4;
                LogEntity logEntity   = new LogEntity();
                logEntity.CategoryId        = _actionType;
                logEntity.OperateTypeId     = _actionType.ToString();
                logEntity.OperateType       = EnumAttribute.GetDescription(GetOperationType(_actionType.ToString()));
                logEntity.OperateAccount    = user.UserName;
                logEntity.OperateUserId     = OperatorProvider.Provider.Current().UserId;
                logEntity.ExecuteResult     = 1;
                logEntity.Module            = SystemInfo.CurrentModuleName;
                logEntity.ModuleId          = SystemInfo.CurrentModuleId;
                logEntity.ExecuteResultJson = "操作信息:推送当前用户到培训平台,建立相关培训及考试任务, 返回结果:" + System.Text.Encoding.UTF8.GetString(e.Result) + ",Json信息:" + e.ToJson();
                logEntity.WriteLog();

                System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("~/logs/" + fileName), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "推送当前用户到培训平台,建立相关培训及考试任务:" + e.ToJson() + "\r\n");
            }
            catch (Exception ex)
            {
                int       _actionType = 5;
                LogEntity logEntity   = new LogEntity();
                logEntity.CategoryId        = _actionType;
                logEntity.OperateTypeId     = _actionType.ToString();
                logEntity.OperateType       = EnumAttribute.GetDescription(GetOperationType(_actionType.ToString()));
                logEntity.OperateAccount    = user.UserName;
                logEntity.OperateUserId     = OperatorProvider.Provider.Current().UserId;
                logEntity.ExecuteResult     = 1;
                logEntity.Module            = SystemInfo.CurrentModuleName;
                logEntity.ModuleId          = SystemInfo.CurrentModuleId;
                logEntity.ExecuteResultJson = "操作信息:推送当前用户到培训平台,建立相关培训及考试任务, 错误信息:" + ex.Message + " , 异常信息:" + ex.InnerException +
                                              " , 异常源:" + ex.Source + " , 异常目标:" + ex.TargetSite + ",异常JSON:" + ex.ToJson();
                logEntity.WriteLog();

                System.IO.File.AppendAllText(HttpContext.Current.Server.MapPath("~/logs/" + fileName), DateTime.Now.ToString("yyyyMMddHHmmss-") + "推送当前用户到培训平台,建立相关培训及考试任务:" + ex.Message + " , 异常信息:" + ex.InnerException +
                                             " , 异常源:" + ex.Source + " , 异常目标:" + ex.TargetSite + ",异常JSON:" + ex.ToJson() + ";\r\n");
            }
        }
        public async Task DeleteSelectedSourcePoint(IEnumerable <Guid> selectedSourcePointIds)
        {
            try
            {
                foreach (var sourcePointId in selectedSourcePointIds)
                {
                    var sourcePoint = _dbContext.SourcePoints.Include(o => o.Catalog).FirstOrDefault(o => o.Id == sourcePointId);
                    if (sourcePoint == null)
                    {
                        throw new NullReferenceException(string.Format("Sourcepoint: {0} is not existed", sourcePointId));
                    }
                    if (sourcePoint.Status != SourcePointStatus.Deleted)
                    {
                        sourcePoint.Status = SourcePointStatus.Deleted;
                    }
                    var task = await _dbContext.SaveChangesAsync();

                    await _logService.WriteLog(new LogEntity()
                    {
                        LogId      = "10003",
                        Action     = Constant.ACTIONTYPE_DELETE,
                        PointType  = Constant.POINTTYPE_SOURCEPOINT,
                        ActionType = ActionTypeEnum.AuditLog,
                        Message    = $"Delete source point named: {sourcePoint.Name} in the excel file named: {sourcePoint.Catalog.FileName}"
                    });
                }
            }
            catch (Exception ex)
            {
                var logEntity = new LogEntity()
                {
                    LogId      = "10006",
                    Action     = Constant.ACTIONTYPE_DELETE,
                    ActionType = ActionTypeEnum.ErrorLog,
                    PointType  = Constant.POINTTYPE_SOURCEPOINT,
                    Message    = ".Net Error",
                    Detail     = ex.ToString()
                };
                logEntity.Subject = $"{logEntity.LogId} - {logEntity.Action} - {logEntity.PointType} - Error";
                await _logService.WriteLog(logEntity);

                throw ex;
            }
        }
Exemple #9
0
        public ActionResult SubmitForm(ModuleButtonEntity moduleButtonEntity, string keyValue)
        {
            var       module = new ModuleApp().GetList().Where(a => a.F_Layers == 1 && a.F_EnCode == moduleName).FirstOrDefault();
            LogEntity logEntity;

            if (string.IsNullOrEmpty(keyValue))
            {
                moduleButtonEntity.F_DeleteMark  = false;
                moduleButtonEntity.F_AllowEdit   = false;
                moduleButtonEntity.F_AllowDelete = false;
                logEntity = new LogEntity(module.F_FullName, "按钮管理", DbLogType.Create.ToString());
                logEntity.F_Description += DbLogType.Create.ToDescription();
            }
            else
            {
                logEntity = new LogEntity(module.F_FullName, "按钮管理", DbLogType.Update.ToString());
                logEntity.F_Description += DbLogType.Update.ToDescription();
                logEntity.F_KeyValue     = keyValue;
            }
            try
            {
                logEntity.F_Account  = OperatorProvider.Provider.GetCurrent().UserCode;
                logEntity.F_NickName = OperatorProvider.Provider.GetCurrent().UserName;
                if (moduleButtonEntity.F_ParentId == "0")
                {
                    moduleButtonEntity.F_Layers = 1;
                }
                else
                {
                    moduleButtonEntity.F_Layers = moduleButtonApp.GetForm(moduleButtonEntity.F_ParentId).F_Layers + 1;
                }
                moduleButtonApp.SubmitForm(moduleButtonEntity, keyValue);
                logEntity.F_Description += "操作成功";
                new LogApp().WriteDbLog(logEntity);
                return(Success("操作成功。"));
            }
            catch (Exception ex)
            {
                logEntity.F_Result       = false;
                logEntity.F_Description += "操作失败," + ex.Message;
                new LogApp().WriteDbLog(logEntity);
                return(Error(ex.Message));
            }
        }
        public string AddLogEntity(LogEntity entitet)
        {
            Database db = new Database();

            entitet.Id = factory.AddLogEntity(entitet);

            if (entitet.Id == null)
            {
                Console.WriteLine("Entitet za grad: {0} i godinu: {1} već postoji!", entitet.Grad, entitet.Godina);
                return(null);
            }

            if (!db.EntityList.ContainsKey(entitet.Id))
            {
                db.EntityList.Add(entitet.Id, entitet);
            }

            return(entitet.Id);
        }
Exemple #11
0
        /// <summary>
        /// Logs http request, requested url and specified items
        /// </summary>
        public override void Log(LogEntity entity, HttpRequest request, string requestedUrl, params object[] optionalData)
        {
            if (ActivityLogEnabled == false)
            {
                return;
            }
            if (entity == LogEntity.ImageRequested && Configurations.LogSystem.ActivityLog_Images == false)
            {
                return;
            }

            // executing plugins
            if (_isPluginAvailable)
            {
                Plugins.CallPluginMethod(PluginHosts.IPluginLogSystem,
                                         PluginMethods.IPluginLogSystem.BeforeLog,
                                         this, request, requestedUrl, optionalData);
            }


            StringBuilder builder = new StringBuilder();

            builder.AppendFormat(_strUrlFormat, requestedUrl);

            if (request != null)
            {
                builder.AppendFormat(_strIPFormat, request.UserHostAddress);
            }
            builder.AppendFormat(_strDateTimeFormat, DateTime.Now.ToString());

            for (int i = 0; i < optionalData.Length; i++)
            {
                builder.AppendFormat(_strDataFormat, optionalData[i]);
            }

            string result = string.Format(_strEntityFormat, entity, builder.ToString());

            try
            {
                SaveToActivityFile(result);
            }
            catch { }
        }
Exemple #12
0
        public Task <int> WriteDbLog(bool result, string resultLog, HttpContext context)
        {
            var userCode = context.User.Claims.First(t => t.Type == OperatorModelClaimNames.UserCode).Value;
            var userName = context.User.Claims.First(t => t.Type == OperatorModelClaimNames.UserName).Value;

            LogEntity logEntity = new LogEntity();

            logEntity.Id       = Common.GuId();
            logEntity.Date     = DateTime.Now;
            logEntity.Account  = userCode;
            logEntity.NickName = userName;
            //logEntityIPAddress = Net.Ip;
            logEntity.IPAddress     = Net.GetIp(context);
            logEntity.IPAddressName = Net.GetLocation(logEntity.IPAddress);
            logEntity.Result        = result;
            logEntity.Description   = resultLog;
            logEntity.AttachCreateInfo(context);
            return(service.InsertAsync(logEntity));
        }
Exemple #13
0
        public ActionResult OutLogin()
        {
            LogEntity logEntity = new LogEntity();

            logEntity.CategoryId        = 1;
            logEntity.OperateTypeId     = ((int)OperationType.Exit).ToString();
            logEntity.OperateType       = EnumAttribute.GetDescription(OperationType.Exit);
            logEntity.OperateAccount    = OperatorProvider.Provider.Current().Account;
            logEntity.OperateUserId     = OperatorProvider.Provider.Current().UserId;
            logEntity.ExecuteResult     = 1;
            logEntity.ExecuteResultJson = "退出系统";
            logEntity.Module            = Config.GetValue("SoftName");
            LogBLL.Instance.WriteLog(logEntity);
            Session.Abandon();                                        //清除当前会话
            Session.Clear();                                          //清除当前浏览器所有Session
            WebHelper.RemoveCookie("dms_autologin");                  //清除自动登录
            //return Content(new AjaxResult { type = ResultType.success, message = "退出系统" }.ToJson());
            return(Success("退出系统"));
        }
Exemple #14
0
        private async Task Insert(string level, string component, string process, string context, string type, string stack,
                                  string msg, DateTime?dateTime)
        {
            var dt        = dateTime ?? DateTime.UtcNow;
            var newEntity = LogEntity.Create(level, component, process, context, type, stack, msg, dt);

            if (level == "error" || level == "fatalerror")
            {
                await _errorTableStorage.InsertAndGenerateRowKeyAsTimeAsync(newEntity, dt);
            }
            if (level == "warning")
            {
                await _warningTableStorage.InsertAndGenerateRowKeyAsTimeAsync(newEntity, dt);
            }
            if (level == "info")
            {
                await _infoTableStorage.InsertAndGenerateRowKeyAsTimeAsync(newEntity, dt);
            }
        }
Exemple #15
0
 public void WriteDbLog(LogEntity logEntity)
 {
     logEntity.F_Id   = Utils.GuId();
     logEntity.F_Date = DateTime.Now;
     try
     {
         logEntity.F_IPAddress     = OperatorProvider.Provider.GetCurrent().LoginIPAddress;
         logEntity.F_IPAddressName = OperatorProvider.Provider.GetCurrent().LoginIPAddressName;
         logEntity.Create();
         service.Insert(logEntity);
     }
     catch (Exception)
     {
         logEntity.F_IPAddress     = Net.Ip;
         logEntity.F_IPAddressName = "本地局域网";
         logEntity.Create();
         service.Insert(logEntity);
     }
 }
Exemple #16
0
        /// <summary>
        /// LADP数据同步日志
        /// </summary>
        /// <param name="strMessage"></param>
        public void LdapDataLog(string strMessage, int intType)
        {
            LogEntity logEntity = new LogEntity();

            logEntity.CategoryId     = intType;
            logEntity.OperateTypeId  = ((int)OperationType.LdapSync).ToString();
            logEntity.OperateType    = EnumAttribute.GetDescription(OperationType.LdapSync);
            logEntity.OperateAccount = "HRUser";
            if (null != OperatorProvider.Provider.Current())
            {
                //logEntity.OperateUserId = OperatorProvider.Provider.Current().UserId;
                logEntity.OperateUserId = "HRUser";
            }
            logEntity.ExecuteResult     = -1;
            logEntity.ExecuteResultJson = strMessage;
            logEntity.Module            = "同步LADP用户";
            logEntity.ModuleId          = "10";
            logEntity.WriteLog();
        }
Exemple #17
0
        public void TestSlackManagerAllowsSameMessageSpamAfterTimeoutWithCustomConfiguration()
        {
            var mutePeriod = TimeSpan.FromSeconds(2);
            // Arrange
            var manager = new LykkeLogToAzureSlackNotificationsManager(_slackNotificationsSenderMock)
                          .SetSpamMutePeriodForLevels(mutePeriod, LogLevel.Warning);

            manager.Start();
            var logEntry = LogEntity.CreateWithoutRowKey(
                LykkeLogToAzureStorage.WarningType, "Component", "Process", "Context", null, null, "Message", DateTime.UtcNow);

            // Act
            manager.SendNotification(logEntry);
            Thread.Sleep(mutePeriod);
            manager.SendNotification(logEntry);

            //Assert
            _slackNotificationsSenderMock.Received(2).SendAsync(Arg.Is <string>(t => t == "Warning"), Arg.Any <string>(), Arg.Any <string>());
        }
Exemple #18
0
        //处理日志行
        private static void ProcessingLogRow(string strLine)
        {
            if (string.IsNullOrWhiteSpace(strLine))
            {
                return;
            }

            strLine = strLine.Trim();

            var logInfo = new LogEntity()
            {
                IP           = Regex.Match(strLine, @"((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))").Value,
                RequestTime  = Regex.Match(strLine, @"(?<=\[)\d+\/\w+\/\d+:\d+:\d+:\d+").Value,
                HttpMethod   = Regex.Match(strLine, @"(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|TRACE)").Value,
                RequestUrl   = Regex.Match(strLine, @"(?<=(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|TRACE) ).*(?=\ HTTP/)").Value,
                ResponseCode = Regex.Match(strLine, @"(?<=HTTP/\d+.\d+.\s)\d*(?=\s\d+\s)").Value,
                //BotName = Regex.Match(strLine, @"(?<=compatible; ).*(?=/\d.\d)").Value,
                BotName = Regex.Match(strLine, @"(" + string.Join('|', bots) + ")").Value,
                //BotVersion = Regex.Match(strLine, @"(?<=compatible;.*/).*(?=;)").Value,
                //UserAgent = Regex.Match(strLine, @"(?<=\s\S-\S\s\S).*/\d+.\d+").Value
            };

            string rowTemplate = @"
            <tr>
                <td>{IP}</td>
                <td>{HttpMethod}</td>
                <td>{ResponseCode}</td>
                <td>{RequestTime}</td>
                <td>{BotName}</td>
                <td>{RequestUrl}</td>
            </tr>";
            string rowContent  = rowTemplate
                                 .Replace("{IP}", logInfo.IP)
                                 .Replace("{HttpMethod}", logInfo.HttpMethod)
                                 .Replace("{ResponseCode}", logInfo.ResponseCode)
                                 .Replace("{RequestTime}", logInfo.RequestTime)
                                 .Replace("{BotName}", logInfo.BotName)
                                 .Replace("{BotVersion}", logInfo.BotVersion)
                                 .Replace("{RequestUrl}", logInfo.RequestUrl)
            ;

            utils.AppendToFile(reportName, rowContent);
        }
        public LogDTO Save(LogEntity entity)
        {
            var transaction = _humanManagerContext.Database.BeginTransaction();

            try
            {
                entity = _humanManagerContext.Logs.Add(entity).Entity;
                _humanManagerContext.SaveChanges();

                transaction.Commit();
                LogDTO dto = _mapper.Map <LogDTO>(entity);
                return(dto);
            }
            catch
            {
                transaction.Rollback();
                return(null);
            }
        }
Exemple #20
0
        public ActionResult OutLogin()
        {
            var       userInfo  = LoginUserInfo.Get();
            LogEntity logEntity = new LogEntity();

            logEntity.F_CategoryId        = 1;
            logEntity.F_OperateTypeId     = ((int)OperationType.Exit).ToString();
            logEntity.F_OperateType       = EnumAttribute.GetDescription(OperationType.Exit);
            logEntity.F_OperateAccount    = userInfo.account + "(" + userInfo.realName + ")";
            logEntity.F_OperateUserId     = userInfo.userId;
            logEntity.F_ExecuteResult     = 1;
            logEntity.F_ExecuteResultJson = "退出系统";
            logEntity.F_Module            = Config.GetValue("SoftName");
            logEntity.WriteLog();
            Session.Abandon();                                          //清除当前会话
            Session.Clear();                                            //清除当前浏览器所有Session
            OperatorHelper.Instance.EmptyCurrent();
            return(Success("退出系统"));
        }
        public ActionResult VisitModule(string moduleId, string moduleName, string moduleUrl)
        {
            LogEntity logEntity = new LogEntity
            {
                CategoryId        = (int)CategoryType.Visit,
                OperateTypeId     = ((int)OperationType.Visit).ToString(),
                OperateType       = OperationType.Visit.GetEnumDescription(),
                OperateAccount    = OperatorProvider.Provider.Current().Account,
                OperateUserId     = OperatorProvider.Provider.Current().UserId,
                ModuleId          = moduleId,
                Module            = moduleName,
                ExecuteResult     = 1,
                ExecuteResultJson = "访问地址:" + moduleUrl
            };

            _logBll.WriteLog(logEntity);

            return(Content(moduleId));
        }
        public static LogEntity GetLogsByUserID(string userID, int tops = 1)
        {
            string tablename = "select top " + tops + " a.*  from UsersLog  a left join M_Users b  on a.UserID =b.UserID ";

            string sqlwhere = " where 1=1 ";

            if (!string.IsNullOrEmpty(userID))
            {
                sqlwhere += " and a.userID='" + userID + "'";
            }
            DataTable dt    = LogDAL.GetDataTable(tablename + sqlwhere + " order by  a.AutoID  desc ");
            LogEntity model = new LogEntity();

            foreach (DataRow dr in dt.Rows)
            {
                model.FillData(dr);
            }
            return(model);
        }
        public LogEntityModel(LogEntity logEntity)
        {
            LogEntityId            = logEntity.LogEntityId;
            EntityName             = logEntity.EntityName;
            EntityFullName         = logEntity.EntityFullName;
            EntityAssembly         = logEntity.EntityAssembly;
            LogActionType          = logEntity.LogActionType;
            OriginalValuesAsString = logEntity.OriginalValues;
            ChangedValuesAsString  = logEntity.ChangedValues;
            CreatedAt     = logEntity.CreatedAt;
            TransactionId = logEntity.TransactionId;
            EntityType    = Assembly.Load(logEntity.EntityAssembly).GetType(logEntity.EntityFullName);

            OriginalValues = JsonConvert.DeserializeObject(logEntity.OriginalValues, EntityType);

            ModifiedEntityProperties = string.IsNullOrEmpty(logEntity.ChangedValues)
                                        ? new ModifiedEntityProperty[] { }
                                        : JsonConvert.DeserializeObject(logEntity.ChangedValues, typeof(ModifiedEntityProperty[])) as ModifiedEntityProperty[];
        }
 public string Serialize(LogEntity logEntity)
 {
     return(JsonConvert.SerializeObject(logEntity, Formatting.Indented, new JsonSerializerSettings
     {
         NullValueHandling = NullValueHandling.Ignore,
         ContractResolver = new LogContractResolver(),
         Converters =
         {
             new LogStringValueConverter(),
             new ReflectionConverter(),
         },
         Error = (sender, args) =>
         {
             args.ErrorContext.Handled = true;
         },
         DateTimeZoneHandling = DateTimeZoneHandling.Local,
         DateFormatString = "yyyy-MM-ddTHH:mm:ss.fff"
     }));
 }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            LogApplication logApplication = new LogApplication();
            LogEntity      logEntity      = new LogEntity();

            logEntity.logType       = LogType.ModifyPassword;
            logEntity.operatingTime = DateTime.Now;
            logEntity.currentUserId = UserInfo.UserID;
            logEntity.referrer      = Context.Request.UrlReferrer.ToString();
            logEntity.iPAddress     = HttpContext.Current.Request.UserHostAddress;

            string msg = "";

            if (!string.IsNullOrEmpty(txtPassword.Text) || !string.IsNullOrEmpty(txtConfirmPassword.Text))
            {
                bool result;
                msg = CheckInput(out result);
                if (!result)
                {
                    ShowMessageToClient(msg, 2, false, false);
                    return;
                }
            }

            UsersEntity user = GetEntity();

            if (userApp.UpdateUser(user))
            {
                ShowSuccessMessageToClient(false, true);
                logEntity.IsSuccess   = true;
                logEntity.Description = UserInfo.UserName + " modifiy " + txtUserName.Text
                                        + " password to" + txtPassword.Text + " success. new password: "******" modifiy " + txtUserName.Text
                                        + " password to" + txtPassword.Text + " fail. msg: " + msg;
            }
            logApplication.Write(logEntity);
        }
Exemple #26
0
        public static bool TryWriteAppLog(this Exception ex, string detail)
        {
            bool result = false;

            if (ex != null)
            {
                LogEntity logEntity = new LogEntity(ex);

                logEntity.LogEventType = ApplicationErrorLogSection.GetSection().GetExceptionLogEventType(ex);

                logEntity.EventID    = ApplicationErrorEventID;
                logEntity.StackTrace = detail;

                HttpContext context = HttpContext.Current;

                try
                {
                    if (context != null)
                    {
                        string[] paths = context.Request.ApplicationPath.Split('/');

                        logEntity.Source = paths[paths.Length - 1];

                        logEntity.Title = string.Format("{0}应用页面错误", context.Request.ApplicationPath);
                        logEntity.ExtendedProperties.Add("RequestUrl", context.Request.Url.AbsoluteUri);
                        logEntity.ExtendedProperties.Add("UserHostAddress", context.Request.UserHostAddress);

                        if (HttpContext.Current.User != null)
                        {
                            logEntity.ExtendedProperties.Add("UserLogOnName", HttpContext.Current.User.Identity.Name);
                        }
                    }
                }
                catch
                {
                }

                result = TryWriteAppLog(logEntity);
            }

            return(result);
        }
        protected string FormatFrames(LogEntity entity)
        {
            StringBuilder builder;

            builder = new StringBuilder();
            foreach (StackFrame frame in entity.Frames)
            {
                MethodBase method;
                string     typeFullName;
                string     methodName;

                method       = frame.GetMethod();
                typeFullName = null;
                methodName   = null;
                if (method != null)
                {
                    typeFullName = method.DeclaringType.FullName;
                    methodName   = method.Name;
                }
                if (typeFullName == null)
                {
                    typeFullName = "{unknown}";
                }
                if (methodName == null)
                {
                    methodName = "{unknown}";
                }
                else if (methodName.Equals(".ctor"))
                {
                    methodName = "{constructor}";
                }
                builder.AppendFormat(
                    this._frameFormat,
                    this._newLine,
                    typeFullName,
                    methodName,
                    frame.GetFileName(),
                    frame.GetFileLineNumber(),
                    frame.GetFileColumnNumber());
            }
            return(builder.ToString());
        }
Exemple #28
0
        public bool UpdateEntity(LogEntity le)
        {
            lock (pblock)
            {
                if (ListaLogEntity.ContainsKey(le.Id))
                {
                    int rupa = NadjiRupu(ListaLogEntity);

                    ListaLogEntity[le.Id] = le;

                    XDocument xmlDoc = XDocument.Parse(File.ReadAllText("baza.xml"));

                    var items = from item in xmlDoc.Descendants("LogEntity")
                                where item.Element("Id").Value == le.Id
                                select item;


                    foreach (XElement ielement in items)
                    {
                        ielement.SetElementValue("Region", le.Region.ToString());
                        ielement.SetElementValue("Grad", le.Grad.ToString());
                        ielement.SetElementValue("Godina", le.Godina.ToString());


                        int i = 0;

                        foreach (var pot in items.Descendants("Potrosnja").Descendants("float"))
                        {
                            pot.SetValue(le.Potrosnja[i]);
                            i++;
                            if (i == le.Potrosnja.Count)
                            {
                                break;
                            }
                        }
                    }
                    xmlDoc.Save("baza.xml");
                    return(true);
                }
                return(false);
            }
        }
Exemple #29
0
        /// <summary>
        /// 空のログを作成する
        /// </summary>
        /// <param name="recordedOn">記録日</param>
        /// <returns>空のログデータ</returns>
        internal LogData CreateEmptyLog(string recordedOn)
        {
            var result = new LogData()
            {
                LogList = new ObservableCollection <LogDetailData>()
            };

            using (var database = new MyLogDatabase(Constants.DatabaseFile())) {
                try {
                    database.Open();
                    var categoryEntity = new CategoryEntity(database);
                    var categories     = new Dictionary <long, string>();
                    using (var recset = categoryEntity.Select()) {
                        while (recset.Read())
                        {
                            if (!recset.GetBool(CategoryEntity.Cols.Visible))
                            {
                                continue;
                            }
                            result.LogList.Add(new LogDetailData()
                            {
                                CategoryId   = recset.GetLong(CategoryEntity.Cols.Id),
                                CategoryName = recset.GetString(CategoryEntity.Cols.Name),
                                IsCategory   = true
                            });
                        }
                    }

                    database.BeginTrans();
                    var logEntity = new LogEntity(database)
                    {
                        RecordedOn = recordedOn
                    };
                    result.Id = logEntity.Insert();
                    database.CommitTrans();
                } catch (Exception ex) {
                    database.RollbackTrans();
                    throw ex;
                }
            }
            return(result);
        }
Exemple #30
0
        public async Task <ThreadWithMessagesResponseModel> AddNewMessageAsync(NewMessageRequestModel newMessage)
        {
            DateTime? readAt;
            LogEntity logEntity        = new LogEntity();
            var       newMessageEntity = _mapper.Map <NewMessageRequestModel, MessageEntity>(newMessage);

            var thread = await _threadRepository.GetAsync(newMessageEntity.ThreadId);

            if (thread == null)
            {
                throw new InvalidRequestException();
            }
            thread.ArchivedBy = new List <int>();
            await _threadRepository.UpdateAsync(thread);

            newMessageEntity.ReadBy.Add(newMessage.FromUserId);
            if (newMessageEntity.ReadBy.Count > 0)
            {
                readAt = DateTime.UtcNow;
            }
            else
            {
                readAt = null;
            }
            newMessageEntity.IsImportant  = newMessage.IsImportant;
            newMessageEntity.FromUserName = newMessage.FromUserName;
            // Add message and Get all messages
            var messages = _mapper.Map <IEnumerable <MessageEntity>, IEnumerable <MessageResponseModel> >(await _messageRepository.AddAndGetAsync(newMessageEntity)).ToList();

            // update thread modified time
            thread.ModifiedAt = DateTime.UtcNow;

            await _threadRepository.UpdateAsync(thread);

            var participantsDetails = _mapper.Map <IEnumerable <ChatUser>, IEnumerable <UserContactResponseModel> >(await _contactRepository.GetChatUserDetailsAsync(thread.Participants));

            var threadWithMessages = _mapper.Map(messages, _mapper.Map <ThreadEntity, ThreadWithMessagesResponseModel>(thread, options => options.Items[MappingConstants.ThreadRequestUserId] = newMessage.FromUserId));

            await LogMessage(thread, messages.OrderByDescending(x => x.CreatedAt).First(), readAt);

            return(_mapper.Map(participantsDetails, threadWithMessages));
        }
Exemple #31
0
        private void Write(string message)
        {
            LogEntity entity = new LogEntity();

            try
            {
                entity.ActivityId = "abc";
                entity.Message    = message;
                entity.TraceLevel = "1";
                entity.UserName   = WindowsIdentity.GetCurrent().Name;
                if (_entLibWriter != null)
                {
                    _entLibWriter.LogToFile(entity);
                }
            }
            catch (Exception ex)
            {
                _eventWriter.WriteToEventLog(entity, ex);
            }
        }
Exemple #32
0
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="log">待写的日志记录对象</param>
        public void Write(LogEntity log)
        {
            ExceptionHelper.FalseThrow(log != null, "LogEntity对象为空");

            try
            {
                UpdateLastMsg(log.Message);

                if (string.IsNullOrEmpty(log.Source))
                {
                    log.Source = this.name;
                }

                this.logger.Write(log);
            }
            catch (Exception ex)
            {
                this.WriteDebugString(ex, EventLogEntryType.Warning, ServiceLogEventID.SERVICEBASE_WRITELOG);
            }
        }
Exemple #33
0
 /// <summary>
 /// 批量杀出
 /// </summary>
 /// <param name="keyValues">主键</param>
 /// <returns></returns>
 public bool DeleteBatch(List <string> keyValues)
 {
     if (keyValues.Count() > 0)
     {
         using (var db = _dbContext.GetIntance())
         {
             var logEntity = new LogEntity();
             logEntity.DeleteMark = 0;
             //逻辑删除
             var counts = db.Updateable(logEntity).UpdateColumns(it => new { it.DeleteMark })
                          .Where(it => keyValues.Contains(it.LogId)).ExecuteCommand();
             result = counts > 0 ? true : false;
         }
     }
     else
     {
         result = false;
     }
     return(result);
 }
 protected override void Append(LogEntity entity, string formatted)
 {
     try
     {
         switch (entity.Level)
         {
             case LogLevel.Fatal:
             case LogLevel.Error:
                 Console.Error.Write(formatted);
                 break;
             default:
                 Console.Out.Write(formatted);
                 break;
         }
     }
     catch
     {
         // do nothing
     }
 }
Exemple #35
0
        public static bool TryWriteAppLog(LogEntity logEntity)
        {
            bool result = false;

            if (logEntity != null)
            {
                try
                {
                    Logger logger = LoggerFactory.Create("webApplicationError");

                    logger.Write(logEntity);
                    result = true;
                }
                catch
                {
                }
            }

            return(result);
        }
Exemple #36
0
        public int Write(LogEntity logEntity)
        {
            BaseValidator <LogEntity> validator = new AddLogValidator();

            if (!validator.Validate(logEntity))
            {
                this.AddBrokenRuleMessages(validator.BrokenRuleMessages);
                return(0);
            }
            this.ClearBrokenRuleMessages();
            int id;

            id = logRepository.Insert(logEntity);
            if (id == 0)
            {
                this.AddBrokenRuleMessage();
                return(0);
            }
            return(id);
        }
Exemple #37
0
        public IHttpActionResult AddAccountSYS(LogEntity log)
        {
            bool         isAddSuccess = false;
            ResultEntity result       = new ResultEntity();

            try
            {
                LOG temp = log.ToLOG();
                isAddSuccess = dal.AddLog(temp);
                result.Data  = log;
            }
            catch (Exception e)
            {
                result.Message = e.Message;
                NtripProxyLogger.LogExceptionIntoFile("调用接口api/Log/AddLog异常,异常信息为:" + e.Message);
            }

            result.IsSuccess = isAddSuccess;
            return(Json <ResultEntity>(result));
        }
 protected override void Append(LogEntity entity, string formatted)
 {
     try
     {
         switch (entity.Level)
         {
             case LogLevel.Fatal:
             case LogLevel.Error:
                 if (this._useFail)
                     Debug.Fail(formatted);
                 else
                     Debug.Write(formatted);
                 break;
             default:
                 Debug.Write(formatted);
                 break;
         }
     }
     catch
     {
         // do nothing
     }
 }
        /// <summary>
        /// 刷新Listener的缓冲区
        /// </summary>
        /// <remarks>
        /// 调用包装的TraceListener类的对应Flush方法
        /// <code source="..\Framework\src\DeluxeWorks.Library\Logging\Logger.cs" lang="cs" region="Process Log" title="写日志"></code>
        /// </remarks>
        public override void Flush()
        {
            using (DbContext context = DbContext.GetContext(logDbConnName))
            {

                using (var scope = new TransactionScope())
                {

                    Database database = DatabaseFactory.Create(context);
                    foreach (LogEntity entity in logEntityList)
                    {
                        try
                        {

                            object logType;
                            if (!entity.ExtendedProperties.TryGetValue("LogType", out logType))
                            {
                                //throw new LogTypeNotDefineException(Properties.Resource.ERR_LOG_ENTITY_NOT_HAVE_TYPE);
                                throw new Exception("未知类型");
                            }

                            InsertSystemLog(entity, database);

                        }
                        catch (Exception exp)
                        {
                            var e = new LogEntity(exp);
                            InsertSystemLog(e, database);
                        }

                    }
                    scope.Complete();
                    logEntityList.Clear();
                }
            }
        }
 private void InsertSystemLog(LogEntity entity, Database database)
 {
     DbCommand command = database.GetSqlStringCommand(string.Format(INSERT_SYSTEM_LOG_SQL, logTableName));
     database.AddInParameter(command, "GUID", DbType.Guid, entity.ExtendedProperties.ContainsKey("Guid") ? entity.ExtendedProperties["Guid"] : Guid.NewGuid());
     database.AddInParameter(command, "LogDate", DbType.DateTime, entity.ExtendedProperties.ContainsKey("LogDate") ? entity.ExtendedProperties["LogDate"] : DateTime.Now);
     database.AddInParameter(command, "LogType", DbType.Int32, entity.ExtendedProperties["LogType"]);
     database.AddInParameter(command, "LogUserLoginID", DbType.String, entity.ExtendedProperties["LogUserLoginID"]);
     database.AddInParameter(command, "LogUserIP", DbType.String, entity.ExtendedProperties["LogUserIP"]);
     database.AddInParameter(command, "LogSummary", DbType.String, GetLogSummary(entity));
     database.AddInParameter(command, "LogDescription", DbType.String, GetLogDescription(entity));
     database.AddInParameter(command, "OperationEntityCharacter", DbType.String, entity.ExtendedProperties.ContainsKey("OperationEntityCharacter") ? entity.ExtendedProperties["OperationEntityCharacter"] : DBNull.Value);
     database.AddInParameter(command, "OperationEntityGuid", DbType.Guid, entity.ExtendedProperties.ContainsKey("OperationEntityGuid") ? new Guid(entity.ExtendedProperties["OperationEntityGuid"].ToString()) : Guid.Empty);
     database.AddInParameter(command, "OperationEntityOriginalValue", DbType.String, entity.ExtendedProperties.ContainsKey("OperationEntityOriginalValue") ? entity.ExtendedProperties["OperationEntityOriginalValue"] : DBNull.Value);
     database.AddInParameter(command, "OperationEntityCurrentValue", DbType.String, entity.ExtendedProperties.ContainsKey("OperationEntityCurrentValue") ? entity.ExtendedProperties["OperationEntityCurrentValue"] : DBNull.Value);
     database.AddInParameter(command, "OperationEntityName", DbType.String, entity.ExtendedProperties.ContainsKey("OperationEntityName") ? entity.ExtendedProperties["OperationEntityName"] : DBNull.Value);
     database.AddInParameter(command, "Level", DbType.Int32, entity.ExtendedProperties["Level"]);
     database.ExecuteNonQuery(command);
 }
        private static string GetLogSummary(LogEntity entity)
        {
            string logSummary = string.Empty;

            if (entity.ExtendedProperties.ContainsKey("LogSummary"))
            {
                logSummary = entity.ExtendedProperties["LogSummary"].ToString();
            }

            if (string.IsNullOrEmpty(logSummary) && (EnumLogType)entity.ExtendedProperties["LogType"] == EnumLogType.ExceptionLog)
            {
                logSummary = entity.Message.Length >= 4000 ? entity.Message.Substring(0, 4000) : entity.Message;
            }

            return logSummary;
        }
 protected abstract void Append(LogEntity entity, string formatted);
 public bool Matches(LogEntity entity)
 {
     return entity.Cause != null;
 }
Exemple #44
0
        internal static LogEntity ConvertLog(LogMessage log)
        {
            LogEntity result = new LogEntity();
            result.Uid = Guid.NewGuid();
            result.Level = log.Level;
            result.Message = log.Message;
            result.SourceDate = log.SourceDate;

            result.UpdateDate = DateTime.Now;

            try
            {
                Guid searchGuid = new Guid(log.ApplicationKey);
               RepositoryContext.Current.Applications.GetById(searchGuid);
            }
            catch(Exception err)
            {
                WlogLogger.Current.Error(err);
            }

            return result;
        }
Exemple #45
0
 public abstract void Log(LogEntity entity, params object[] optionalData);
 public void Append(LogEntity entity)
 {
     this.Append(entity, this.FormatMessage(entity));
 }
 protected string FormatMessage(LogEntity entity)
 {
     return String.Format(
         this._messageFormat,
         this._newLine,
         entity.Timestamp,
         entity.ProcessId,
         entity.ManagedThreadId,
         entity.Source.Name,
         System.Enum.Format(typeof(LogLevel), entity.Level, "G").ToUpper(),
         entity.Message,
         this.FormatFrames(entity),
         this.FormatCauses(entity));
 }
        protected string FormatCauses(LogEntity entity)
        {
            StringBuilder builder;
            Exception cause;

            builder = new StringBuilder();
            cause = entity.Cause;
            while (cause != null)
            {
                builder.AppendFormat(
                    this._causeFormat,
                    this._newLine,
                    cause,
                    cause.GetType().FullName,
                    cause.Message,
                    cause.StackTrace);
                cause = cause.InnerException;
            }
            return builder.ToString();
        }
        protected string FormatFrames(LogEntity entity)
        {
            StringBuilder builder;

            builder = new StringBuilder();
            foreach (StackFrame frame in entity.Frames)
            {
                MethodBase method;
                string typeFullName;
                string methodName;

                method = frame.GetMethod();
                typeFullName = null;
                methodName = null;
                if (method != null)
                {
                    typeFullName = method.DeclaringType.FullName;
                    methodName = method.Name;
                }
                if (typeFullName == null)
                    typeFullName = "{unknown}";
                if (methodName == null)
                    methodName = "{unknown}";
                else if (methodName.Equals(".ctor"))
                    methodName = "{constructor}";
                builder.AppendFormat(
                    this._frameFormat,
                    this._newLine,
                    typeFullName,
                    methodName,
                    frame.GetFileName(),
                    frame.GetFileLineNumber(),
                    frame.GetFileColumnNumber());
            }
            return builder.ToString();
        }
 public void Append(LogEntity entity)
 {
     // do nothing
 }
 public bool Matches(LogEntity log)
 {
     return !this._matcher.Matches(log);
 }
Exemple #52
0
        /// <summary>
        /// Logs http request, requested url and specified items
        /// </summary>
        public override void Log(LogEntity entity, HttpRequest request, string requestedUrl, params object[] optionalData)
        {
            if (ActivityLogEnabled == false)
                return;
            if (entity == LogEntity.ImageRequested && Configurations.LogSystem.ActivityLog_Images == false)
                return;

            // executing plugins
            if (_isPluginAvailable)
                Plugins.CallPluginMethod(PluginHosts.IPluginLogSystem,
                    PluginMethods.IPluginLogSystem.BeforeLog,
                    this, request, requestedUrl, optionalData);

            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(_strUrlFormat, requestedUrl);

            if (request != null)
                builder.AppendFormat(_strIPFormat, request.UserHostAddress);
            builder.AppendFormat(_strDateTimeFormat, DateTime.Now.ToString());

            for (int i = 0; i < optionalData.Length; i++)
            {
                builder.AppendFormat(_strDataFormat, optionalData[i]);
            }

            string result = string.Format(_strEntityFormat, entity, builder.ToString());

            try
            {
                SaveToActivityFile(result);
            }
            catch { }
        }
 public bool Matches(LogEntity entity)
 {
     return this._level < entity.Level;
 }
Exemple #54
0
 public void PersistLog(LogMessage log)
 {
     LogEntity ent = new LogEntity();
     ent.ApplictionId = RepositoryContext.Current.Applications.GetByApplicationKey(log.ApplicationKey).IdApplication;
     ent.Level = log.Level;
     ent.Message = log.Message;
     ent.SourceDate = log.SourceDate;
     ent.UpdateDate = DateTime.Now;
     ent.CreateDate = DateTime.Now;
     RepositoryContext.Current.Logs.Save(ent);
 }
Exemple #55
0
 public override void Log(LogEntity entity, string requestedUrl, params object[] optionalData)
 {
     Log(entity, null, requestedUrl, optionalData);
 }
Exemple #56
0
 public abstract void Log(LogEntity entity, HttpRequest request, string requestedUrl, params object[] optionalData);
 public bool Matches(LogEntity entity)
 {
     return this._matcher.Matches(entity.Source);
 }
        /// <summary>
        /// 重载方法,写入数据
        /// </summary>
        /// <param name="eventCache">包含当前进程 ID、线程 ID 以及堆栈跟踪信息的 TraceEventCache 对象</param>
        /// <param name="source">标识输出时使用的名称,通常为生成跟踪事件的应用程序的名称</param>
        /// <param name="logEventType">TraceEventType枚举值,指定引发日志记录的事件类型</param>
        /// <param name="eventID">事件的数值标识符</param>
        /// <param name="data">要记录的日志数据</param>
        /// <remarks>
        /// 只有Formatter属性不为空时,才格式化
        /// <code source="..\Framework\src\DeluxeWorks.Library\Logging\Logger.cs" lang="cs" region="Process Log" title="写日志"></code>
        /// </remarks>
        public override void TraceData(TraceEventCache eventCache, string source, TraceEventType logEventType, int eventID, object data)
        {
            //throw new LogException(ERROR_MESSAGE);
            if (data is LogEntity)
            {
                var logData = data as LogEntity;
                logEntityList.Add(logData);

            }
            else
            {
                var entity = new LogEntity(data.ToString(), data.ToString(), eventID, LogPriority.Normal, logEventType, source, eventCache.Callstack, null);
                logEntityList.Add(entity);
            }
        }
        private static string GetLogDescription(LogEntity entity)
        {
            string logDesc = string.Empty;

            if (entity.ExtendedProperties.ContainsKey("LogDescription"))
            {
                logDesc = entity.ExtendedProperties["LogDescription"].ToString();
            }

            if (string.IsNullOrEmpty(logDesc) && (EnumLogType)entity.ExtendedProperties["LogType"] == EnumLogType.ExceptionLog)
            {
                var sbExpMsg = new StringBuilder();

                sbExpMsg.Append("Title:");
                sbExpMsg.Append(entity.Title);
                sbExpMsg.Append(Environment.NewLine);
                sbExpMsg.Append("Type:");
                sbExpMsg.Append(entity.LogEventType);
                sbExpMsg.Append(Environment.NewLine);
                sbExpMsg.Append("CallStack:");
                sbExpMsg.Append(entity.StackTrace);
                sbExpMsg.Append(Environment.NewLine);

                logDesc = sbExpMsg.ToString();
            }

            return logDesc;
        }
 public virtual void Append(LogEntity entity)
 {
     this._appender.Append(entity);
 }