功能?班级?

发布于 2024-11-30 05:46:29 字数 499 浏览 1 评论 0原文

我正在编写一个应用程序 (C#),有时我需要记录到 Windows 事件日志。因此,我想到的第一件事就是在我唯一的类中编写一个函数,并在需要时调用它。像这样的事情:

private void Write_Event_Log(string log, string source, string message, EventLogEntryType type, int eventid)
    {
        if (!EventLog.SourceExists(source))
            EventLog.CreateEventSource(source, log);

        EventLog.WriteEntry(source, message, type, eventid);
    }

我的一位同事问,“为什么不为事件日志编写器创建一个新类?”所以我的问题是,我为什么要这样做?这个类会是什么样子呢?当我的函数运行良好时,为什么我需要它?好吧,这是 3 个问题,但你明白了:)

I'm writing an app (C#) and at times I will need to log to the Windows event log. So the first thing that comes to mind is to write a function in my one and only class and call it when I need it. Something like this:

private void Write_Event_Log(string log, string source, string message, EventLogEntryType type, int eventid)
    {
        if (!EventLog.SourceExists(source))
            EventLog.CreateEventSource(source, log);

        EventLog.WriteEntry(source, message, type, eventid);
    }

A colleague of mine asked, "why didn't you just create a new class for your event log writer?" So my question is, why would I? And what would this class even look like? And why would I need it when my function works nicely? ok that's 3 questions but you get the point :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

被翻牌 2024-12-07 05:46:29

我为什么要这么做?

将日志记录功能封装到它自己的类中。为什么?单一职责原则 http://en.wikipedia.org/wiki/Single_responsibility_principle。如果将它混合到您的类中,您将使该类负责至少两 (2) 件事:无论它做什么和记录。

这个类会是什么样子?

public class LogWriter
{
    public static Log(string log, string source, string message, EventLogEntryType type, int eventid)
    {
        if (!EventLog.SourceExists(source))
            EventLog.CreateEventSource(source, log);

            EventLog.WriteEntry(source, message, type, eventid);
    }
}

当我的函数运行良好时,为什么还需要它?

想想什么时候你不再对代码负责。提前考虑代码何时增长。最终,除了日志记录之外,它可能还包含许多其他非常有用的功能。下一个程序员会更高兴不必重构你的工作,因为设计先例已经确定。

why would I?

To encapsulate the logging functionality into its own class. Why? Single Responsibility Principle http://en.wikipedia.org/wiki/Single_responsibility_principle. Ny mixing it into your class you are making that class be responsible for at least two (2) things: whatever it does and logging.

And what would this class even look like?

public class LogWriter
{
    public static Log(string log, string source, string message, EventLogEntryType type, int eventid)
    {
        if (!EventLog.SourceExists(source))
            EventLog.CreateEventSource(source, log);

            EventLog.WriteEntry(source, message, type, eventid);
    }
}

And why would I need it when my function works nicely?

Think about when you are no longer responsible for the code. Think ahead to when the code grows. Eventually, in addition to logging it might have a host of other very helpful functions included in it. The next programmer would be much happier not having to refactor your work because the design precedent has been set.

风尘浪孓 2024-12-07 05:46:29

这是关于 OO 设计的一个非常普遍的问题。你的同事指的是职责分离;他认为事件日志写入器的想法不适合您放入的类的抽象,并且它值得拥有自己的抽象。

如果这就是您要使用它的全部目的(这一个方法),并且该程序足够简单,您可以在一个类中实现它,则无需使用另一个类与您的事件编写器交互。如果您可以设想您的事件编写器将来可能会以不同的方式或由不同的类使用,那么是的,绝对将其设为自己的类,这样您就可以避免将来出现必须更改源代码的问题使用它。

您编写的函数是一个不保持状态的小函数,因此除非是为了避免将来出现问题,否则实际上不需要另一个类。

This is a very general question about OO design. Your colleague is referring to separation of responsibilities; he doesn't think that the idea of an event log writer fits into the abstraction of the class you put it in, and it deserves its own.

If this is all you are ever going to use it for (this one method) and this program is simple enough that you are implementing it one class, there is no need to use another class to interact with your event writer. If you can conceive that your event writer might be used in a different way, or by a different class, in the future, then yes, absolutely make it is own class so that you avoid future problems where you have to change the source code that uses it.

The function you've written is a small function that doesn't keep state, so another class is not really necessary unless it's to avoid future problems.

完美的未来在梦里 2024-12-07 05:46:29

很简单,如果您希望在代码库的所有其他部分的任何地方都使用此方法怎么办?您再次复制-粘贴。相反,在类中添加一个助手或 Add,只需实例化并继续调用即可。

另外,如果它在一个类中,您可以拥有更多属性并在记录数据时提供更多自定义方法。

看看是否可以使用内置的事件日志/跟踪内容。

Simple, what if you wish to use this method every where in all other parts of your code base? You again copy - paste. Instead have a helper or a Add in class, where just instantiate and keep calling.

Plus if its in a class, you can have more properties and provide more customization methods as well in logging data.

See if you can make use of built in eventlog/trace stuffs.

扛起拖把扫天下 2024-12-07 05:46:29

如果它是一个小型应用程序(它必须是一个类),那么它可能并不重要。

但在较大的应用程序中,明智的设计是,您可能需要考虑将日志记录功能单独放在一个类中,以使每个类尽可能集中。

If it's a small application (which with one class it must be) then it probably doesn't matter.

But design wise in a larger application, you probably would want to consider having the logging functionality in a class by itself in order to keep each class as narrowly focused as possible.

童话 2024-12-07 05:46:29

出于同样的原因,有人将 SourceExists(Source)CreateEventSource(source, log) 放入自己的类中,因此您只需引用具有该类的程序集即可调用它们定义类,并写入

 EventLog.SourceExists(source);

 EventLog.CreateEventSource(source, log);

因此,如果您永远不会需要在您编写的任何其他应用程序中写入事件日志,那么您所做的就很好。但如果您可能再次需要这个,那么......

For the same reason that someone put SourceExists(Source) and CreateEventSource(source, log) into their own class, so you could call them just by referencing the assembly that has that class defined, and writing

 EventLog.SourceExists(source);

or

 EventLog.CreateEventSource(source, log);

So if you will never ever need to write to the event log in any other application you ever write, then what you are doing is fine... but if you might ever need this again, then .....

朮生 2024-12-07 05:46:29

我认为你应该有单独的类,因为如果你要在应用程序中创建更多的类,你可以对所有类使用相同的日志记录,请参见下面的示例
公共静态类记录器
{
私有静态字符串 logFilePath = string.Empty;

    public static void Log(string logMessage, TextWriter w)
    {
        w.Write( logMessage);
        w.Flush();
    }


    public static void Log(string textLog)
    {
        string directoryString =
      filepath+           @"\Logging";
        Directory.CreateDirectory(directoryString);

        logFilePath = directoryString + "\\" +
          DateTime.Now.ToShortDateString().Replace("/", "") + ".txt";


        StreamWriter sw = null;
        if (!File.Exists(logFilePath))
        {
            try
            {
                sw = File.CreateText(logFilePath);
            }
            finally
            {
                if (sw != null) sw.Dispose();
            }
        }
        using (StreamWriter w = File.AppendText(logFilePath))
        {
            Log(textLog, w);
            w.Close();
        }
    }

I think you should have seperate class because if you are going to create more no.of classes in your application you can use same logging for all of them see below example
public static class Logger
{
private static string logFilePath = string.Empty;

    public static void Log(string logMessage, TextWriter w)
    {
        w.Write( logMessage);
        w.Flush();
    }


    public static void Log(string textLog)
    {
        string directoryString =
      filepath+           @"\Logging";
        Directory.CreateDirectory(directoryString);

        logFilePath = directoryString + "\\" +
          DateTime.Now.ToShortDateString().Replace("/", "") + ".txt";


        StreamWriter sw = null;
        if (!File.Exists(logFilePath))
        {
            try
            {
                sw = File.CreateText(logFilePath);
            }
            finally
            {
                if (sw != null) sw.Dispose();
            }
        }
        using (StreamWriter w = File.AppendText(logFilePath))
        {
            Log(textLog, w);
            w.Close();
        }
    }
扎心 2024-12-07 05:46:29

我同意您不应该创建一个新类来直接写入事件日志,而是出于另一个原因。该类已经存在!

考虑使用 System.Diagnostics 中的内置调试/跟踪机制:

调试输出

跟踪输出

这些是将信息转储到 TraceListener 对象集合的标准类,其中已经存在许多有用的类型:

< a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.defaulttracelistener.aspx" rel="nofollow noreferrer">DefaultTraceListener - 将输出转储到标准调试输出,我相信是通过 OutputDebugString() 实现的。

EventLogTraceListener - 转储输出到 Windows 事件日志。

因此,这会将您的输出机制从程序问题更改为配置问题。 (是的,如果您使用的是直接托管应用程序,则可以通过 app.config 填充您的 TraceListener 集合。)这意味着您在任何地方都只需使用适当的 Trace。 Write()Debug.Write() 调用(取决于您是否希望在发布版本中输出),并且配置决定输出的位置。

当然,您也可以通过编程方式填充 TraceListener 集合,这既有趣又简单。

这样您就不必建立自己的本地日志记录基础设施。一切都是内置的!使用它祝身体健康! :D


另一方面,如果你坚持自己推出(我认为这是一个坏主意),你的同事是对的。这是一个单独的职责,属于一个单独的类。我希望输出使用静态方法,因为调试日志可能没有概念实例。事实上,我希望有一个与 System.Diagnostics.Debug 非常相似的界面,所以是的,只需使用该界面即可。


根据您的方法,您可能会遇到文档中的微妙陷阱,但如果不仔细阅读,则不会立即明显。 我在其他地方找到了答案

I agree that you shouldn't create a new class for writing directly to the event log, but for another reason. That class already exists!

Consider using the built-in debug/tracing mechanisms in System.Diagnostics:

Debug output

Trace output

These are standard classes that dump information to a collection of TraceListener objects, of which many useful types already exist:

DefaultTraceListener - Dumps output to standard debug out, I believe via OutputDebugString().

EventLogTraceListener - Dumps output to the windows event log.

So this changes your output mechanism from a programmatic question into a configuration question. (Yes, if you're working in a straight-up managed app, you can populate your TraceListener collection via your app.config.) That means that everywhere you simply use the appropriate Trace.Write() or Debug.Write() call (Depending on if your want the output in a release build), and the configuration determines where the output goes.

Of course, you can also populate your TraceListener collection programmatically, it's fun and simple.

And this way you don't have to build up your own home-grown logging infrastructure. It's all built-in! Use it in good health! :D


If, on the other hand, you insist on rolling your own (a bad idea, I think), your colleague is right. It's a separate responsibility and belongs in a separate class. I would expect static methods for output because there's probably no concept instances of your debug log. In fact, I'd expect an interface very similar to System.Diagnostics.Debug, so yeah, just use that one instead.


Depending on your approach, you may run into a subtle gotcha' that's in the docs, but not immediately obvious without a careful reading. I found an answer for it elsewhere.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文