0

I have to log different actions on site. For example, CRUD operations. It's not simple message: "Entity is saved". For different entity various parameters. For example, when changing user I have to save ID, personal number also, for business trip entity I have to save begin and end dates of business trip. This is my code for updating user:

public UserController : Controller
{
   public ActionResult Update(...)
   {
       if (ModelState.IsValid)
       {
          ...
           var id =  _repository.SaveOrUpdate(user);
            _eventLogger.WriteEventLog(new EventLoggerData
                    {
                        EventType = EventLogType.Update,
                        ObjectType = ObjectType.User,
                        ObjectId = id,
                        EventData = _jsonObjectMapper.ToJson(new NumberedEventLoggerData
                        {                                
                            Number = number
                        })
                    });
       }
   }
}

All works fine. But the code :

 _eventLogger.WriteEventLog(new EventLoggerData
       {
             EventType = EventLogType.Update,
             ObjectType = ObjectType.User,
             ObjectId = id,
             EventData = _jsonObjectMapper.ToJson(new NumberedEventLoggerData
                 {
                    Number = number
                 })
        });

is the big and this piece of the code will be repeated more than once. I have about 20 controllers and each with CRUD operations.

May be there are more flexible way?
Sorry for my English.

4

1 回答 1

0

1) 创建更多的 WriteEventLog 重载,使控制器中的代码更简单;类似 WriteEventLog(User) 的东西,适用于所有场合。

2)你使用什么样的ORM?EntityFramework 有 SavingChanges 事件,例如,您可以在其中检查所做的更改并记录它们(我已经这样做了,效果很好)

3) 看看 PostSharp ( http://www.postsharp.net/ ),它可能允许您将日志完全移出控制器,只需要一个属性。

于 2013-10-15T10:32:01.247 回答