Gravar no Registo de eventos da aplicação do Windows

Existe uma maneira de escrever para este registo de eventos:

enter image description here

ou, pelo menos, algum outro registo predefinido do Windows, Onde Não tenho de registar uma fonte de Eventos?

Author: Gianluca Ghettini, 2014-09-08

5 answers

Sim, há uma maneira de escrever para o registo de eventos que está à procura. Você não precisa criar uma nova fonte, basta usar a existente, que muitas vezes tem o mesmo nome que o nome do EventLog e também, em alguns casos como a aplicação de log de eventos, Pode ser acessível sem privilégios administrativos*.

* outros casos, onde você não pode acessá-lo diretamente, são o Security EventLog, por exemplo, que só é acessado pelo sistema operacional.

Usei este código para escreva directamente para a aplicação de registo de Eventos:

using (EventLog eventLog = new EventLog("Application")) 
{
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 
}

Como pode ver, a fonte do EventLog é a mesma que o nome do EventLog. A razão disto pode ser encontrada em Fontes de eventos @ Windows Dev Center (aparafusei a parte que se refere ao nome de código):

Cada registo na chave de Eventlog contém sub-chaves chamadas fontes de eventos. A fonte do evento é o nome do software que regista o evento. é frequentemente o nome da aplicação ou o nome de uma subcomponente do pedido, se o pedido for grande. Você pode adicionar um máximo de 16.384 fontes de eventos para o registro.

 142
Author: cloud120, 2016-01-05 08:23:14

Pode usar a classe EventLog, como explicado em Como: Escrever no Registo de eventos da aplicação (Visual C#):

var appLog = new EventLog("Application");
appLog.Source = "MySource";
appLog.WriteEntry("Test log message");

No entanto, terá de configurar esta fonte "MySource" usando privilégios administrativos:

Utilize WriteEvent e WriteEntry para escrever eventos num registo de eventos. Você precisa indicar uma fonte de eventos para escrever eventos; você precisa criar e configurar o código de eventos antes de escrever o primeiro item com o código.

 9
Author: CodeCaster, 2014-09-08 13:22:15

Ajuda.

A propósito, podes arranjar um obturador de objectos na internet. Não queria pôr isso tudo aqui. Eu trato do meu a partir daqui.: C:\Program Files (x86)\Microsoft Visual Studio 10.0\Samples\1033\CSharpSamples.zip\LinqSamples\ObjectDumper
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Xanico.Core.Utilities;

namespace Xanico.Core
{
    /// <summary>
    /// Logging operations
    /// </summary>
    public static class Logger
    {
        // Note: The actual limit is higher than this, but different Microsoft operating systems actually have
        //       different limits. So just use 30,000 to be safe.
        private const int MaxEventLogEntryLength = 30000;

        /// <summary>
        /// Gets or sets the source/caller. When logging, this logger class will attempt to get the
        /// name of the executing/entry assembly and use that as the source when writing to a log.
        /// In some cases, this class can't get the name of the executing assembly. This only seems
        /// to happen though when the caller is in a separate domain created by its caller. So,
        /// unless you're in that situation, there is no reason to set this. However, if there is
        /// any reason that the source isn't being correctly logged, just set it here when your
        /// process starts.
        /// </summary>
        public static string Source { get; set; }

        /// <summary>
        /// Logs the message, but only if debug logging is true.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="debugLoggingEnabled">if set to <c>true</c> [debug logging enabled].</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogDebug(string message, bool debugLoggingEnabled, string source = "")
        {
            if (debugLoggingEnabled == false) { return; }

            Log(message, EventLogEntryType.Information, source);
        }

        /// <summary>
        /// Logs the information.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogInformation(string message, string source = "")
        {
            Log(message, EventLogEntryType.Information, source);
        }

        /// <summary>
        /// Logs the warning.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogWarning(string message, string source = "")
        {
            Log(message, EventLogEntryType.Warning, source);
        }

        /// <summary>
        /// Logs the exception.
        /// </summary>
        /// <param name="ex">The ex.</param>
        /// <param name="source">The name of the app/process calling the logging method. If not provided,
        /// an attempt will be made to get the name of the calling process.</param>
        public static void LogException(Exception ex, string source = "")
        {
            if (ex == null) { throw new ArgumentNullException("ex"); }

            if (Environment.UserInteractive)
            {
                Console.WriteLine(ex.ToString());
            }

            Log(ex.ToString(), EventLogEntryType.Error, source);
        }

        /// <summary>
        /// Recursively gets the properties and values of an object and dumps that to the log.
        /// </summary>
        /// <param name="theObject">The object to log</param>
        [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Xanico.Core.Logger.Log(System.String,System.Diagnostics.EventLogEntryType,System.String)")]
        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")]
        public static void LogObjectDump(object theObject, string objectName, string source = "")
        {
            const int objectDepth = 5;
            string objectDump = ObjectDumper.GetObjectDump(theObject, objectDepth);

            string prefix = string.Format(CultureInfo.CurrentCulture,
                                          "{0} object dump:{1}",
                                          objectName,
                                          Environment.NewLine);

            Log(prefix + objectDump, EventLogEntryType.Warning, source);
        }

        private static void Log(string message, EventLogEntryType entryType, string source)
        {
            // Note: I got an error that the security log was inaccessible. To get around it, I ran the app as administrator
            //       just once, then I could run it from within VS.

            if (string.IsNullOrWhiteSpace(source))
            {
                source = GetSource();
            }

            string possiblyTruncatedMessage = EnsureLogMessageLimit(message);
            EventLog.WriteEntry(source, possiblyTruncatedMessage, entryType);

            // If we're running a console app, also write the message to the console window.
            if (Environment.UserInteractive)
            {
                Console.WriteLine(message);
            }
        }

        private static string GetSource()
        {
            // If the caller has explicitly set a source value, just use it.
            if (!string.IsNullOrWhiteSpace(Source)) { return Source; }

            try
            {
                var assembly = Assembly.GetEntryAssembly();

                // GetEntryAssembly() can return null when called in the context of a unit test project.
                // That can also happen when called from an app hosted in IIS, or even a windows service.

                if (assembly == null)
                {
                    assembly = Assembly.GetExecutingAssembly();
                }


                if (assembly == null)
                {
                    // From http://stackoverflow.com/a/14165787/279516:
                    assembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
                }

                if (assembly == null) { return "Unknown"; }

                return assembly.GetName().Name;
            }
            catch
            {
                return "Unknown";
            }
        }

        // Ensures that the log message entry text length does not exceed the event log viewer maximum length of 32766 characters.
        private static string EnsureLogMessageLimit(string logMessage)
        {
            if (logMessage.Length > MaxEventLogEntryLength)
            {
                string truncateWarningText = string.Format(CultureInfo.CurrentCulture, "... | Log Message Truncated [ Limit: {0} ]", MaxEventLogEntryLength);

                // Set the message to the max minus enough room to add the truncate warning.
                logMessage = logMessage.Substring(0, MaxEventLogEntryLength - truncateWarningText.Length);

                logMessage = string.Format(CultureInfo.CurrentCulture, "{0}{1}", logMessage, truncateWarningText);
            }

            return logMessage;
        }
    }
}
 8
Author: Bob Horn, 2014-09-08 13:28:34

Como indicado em MSDN (eg. https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog (v=vs. 110).aspx ), verificar uma fonte não existente e criar uma fonte requer privilégio de administração.

É, no entanto, possível utilizar a fonte "Application" sem. No meu teste no Windows 2012 Server r2, no entanto, obtenho o seguinte registo usando a fonte" Application":

A descrição do ID do evento xxxx da aplicação de origem não pode ser encontrado. Ou o componente que levanta este evento não está instalado em seu computador local ou a instalação está corrompida. Você pode instalar ou reparar o componente no computador local. Se o evento teve origem em outro computador, a informação display teve que ser salvo com o evento. As seguintes informações foram incluídas com o evento: {minha mensagem de entrada de eventos} o recurso de mensagens está presente, mas a mensagem não é encontrada na tabela string / message

Eu defini o seguinte método para criar a fonte:

    private string CreateEventSource(string currentAppName)
    {
        string eventSource = currentAppName;
        bool sourceExists;
        try
        {
            // searching the source throws a security exception ONLY if not exists!
            sourceExists = EventLog.SourceExists(eventSource);
            if (!sourceExists)
            {   // no exception until yet means the user as admin privilege
                EventLog.CreateEventSource(eventSource, "Application");
            }
        }
        catch (SecurityException)
        {
            eventSource = "Application";
        }

        return eventSource;
    }

Estou a chamá-lo com actual appname = AppDomain.A corrente continua.FriendlyName

Pode ser possível usar a classe EventLogPermission em vez desta tentativa / captura, mas não sei se podemos evitar a captura.

Também é possível criar a fonte externamente, por exemplo em Powershell elevada:

New-EventLog -LogName Application -Source MyApp

Então, usando 'MyApp' no método acima não irá gerar exceção e o EventLog pode ser criado com essa fonte.

 4
Author: EricBDev, 2017-06-15 11:03:56

Tenta

   System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
   appLog.Source = "This Application's Name";
   appLog.WriteEntry("An entry to the Application event log.");
 -3
Author: ITevfik, 2014-09-08 13:25:07