Which design pattern would you consider when Logging is needed?

后端 未结 5 1924
悲哀的现实
悲哀的现实 2021-02-02 00:11

An application I\'m working on requires logging of actions, user who performs the action, and time of action to a database.

Which design pattern is most popular/appropri

相关标签:
5条回答
  • 2021-02-02 00:55

    I agree, I think the command pattern would fit the most since you would have all the action listed.

    But I don't think that you really need to follow a design specific pattern for this one.You can simply set a callback on the actions to update the log. It depends on your architecture and technologies but out of my head the command pattern sounds like overkill.

    0 讨论(0)
  • 2021-02-02 00:56

    The command pattern sounds fine. It especially enables you to pass the logger to the command and let the command perform the log operation on the logger. In this way you can have each action care for formatting of the log itself and if some actions should not be logged or need special information you overall architecture don't need to know about it. The downside is the coupling of the actions to the logger if you want to to avert this you could give every action a method that returns a log string that should be added.

    If you will have a lots of different actions I don't think this is overkill, if that are only database actions and you can have the database framework perform actions at every database action it may be reinventing the wheel to have a one logging mechanism but as marcgg points out this depends on you architecture.

    0 讨论(0)
  • 2021-02-02 01:00

    Don't conflate the Command and the logging Memento.

    The Command is something that gets done. Which may include some common aspects across all commands, including writing a log entry.

    The log entry itself may be a Memento or a summary of a Memento.

    The logger is a kind of Factory, which creates Mementos for logged events.

    As with most things, you have a large number of interlocking design patterns. Which "one" pattern is "most popular/appropriate" doesn't enter into it.

    The question is "what is supposed to be happening?"

    0 讨论(0)
  • 2021-02-02 01:01

    You can use AOP to apply logging without any intrusive behavior. AOP may feel like a mixture of Proxy and Decorator Pattern.

    0 讨论(0)
  • 2021-02-02 01:07

    Observer Pattern is well suited for logging framework. You can have Logger class extending Observable, and child classes like log to console, log to Database and log to File system etc and each child class implements Observer. Now whenever a log message is logged all the observer classes registered with Logger class will be notified so that each Child class ex: log to console will log the message to console. Also Logger class can follow Singleton pattern to make sure a single instance of Logger is available through out application.

    0 讨论(0)
提交回复
热议问题