¿Cómo puedo iniciar sesión en C # sin usar bibliotecas de terceros?


Me gustaría implementar el registro en mi aplicación, pero preferiría no usar ningún framework externo como log4net.

Así que me gustaría hacer algo como el eco de DOS a un archivo. ¿Cuál es la forma más efectiva de hacerlo?

¿Hay alguna forma de registrar excepciones no controladas registradas sin usar un marco externo?

Author: Tatranskymedved, 2011-02-20

10 answers

public void Logger(String lines)
{

 // Write the string to a file.append mode is enabled so that the log
 // lines get appended to  test.txt than wiping content and writing the log

  System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt",true);
  file.WriteLine(lines);

  file.Close();

}

Para más información MSDN :

 62
Author: Brandon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-07 09:03:22

Puede utilizar el sistema integrado .Diagnostico.TraceSource .
Aquí hay una lista de los oyentes de rastreo integrados + FileLogTraceListener .

Hay muchos manuales en la web como este, o esta otra por Jeff Atwood+mejoras.

 35
Author: HuBeZa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-20 14:47:20

Preferiría no usar ningún exterior frameworks como log4j.net.

¿Por qué? Log4net probablemente abordaría la mayoría de sus requisitos. Por ejemplo, compruebe esta clase: RollingFileAppender.

Log4net está bien documentado y hay miles de recursos y casos de uso en la web.

 24
Author: empi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-20 14:26:45

Puede escribir directamente en un registro de eventos. Compruebe los siguientes enlaces:
http://support.microsoft.com/kb/307024
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx

Y aquí está la muestra de MSDN:

using System;
using System.Diagnostics;
using System.Threading;

class MySample{

    public static void Main(){

        // Create the source, if it does not already exist.
        if(!EventLog.SourceExists("MySource"))
        {
             //An event log source should not be created and immediately used.
             //There is a latency time to enable the source, it should be created
             //prior to executing the application that uses the source.
             //Execute this sample a second time to use the new source.
            EventLog.CreateEventSource("MySource", "MyNewLog");
            Console.WriteLine("CreatedEventSource");
            Console.WriteLine("Exiting, execute the application a second time to use the source.");
            // The source is created.  Exit the application to allow it to be registered.
            return;
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "MySource";

        // Write an informational entry to the event log.    
        myLog.WriteEntry("Writing to event log.");

    }
}
 14
Author: šljaker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-20 14:46:20

Si usted está buscando una manera simple real de registro, puede utilizar este forro. Si el archivo no existe, se crea.

System.IO.File.AppendAllText(@"c:\log.txt", "mymsg\n");
 13
Author: live-love,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-07 09:41:28

Solía escribir mi propio registro de errores hasta que descubrí ELMAH. Nunca he sido capaz de conseguir la parte de correo electrónico tan perfectamente como lo hace ELMAH.

 7
Author: jonezy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-17 07:35:11

Si quieres permanecer cerca de.NET echa un vistazo a Enterprise Library Logging Application Block. Mira aquí. O para un tutorial de inicio rápido, compruebe este. He utilizado el Bloque de aplicación de validación de la Biblioteca Enterprise y realmente se adapta a mis necesidades y es muy fácil de "heredar" (instalarlo y refrence él!) en su proyecto.

 6
Author: Bernoulli IT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-20 14:48:31

Estoy usando NLOG. Es brillante.

 4
Author: ray pixar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-24 11:24:18

Si desea su propio registro de errores personalizado, puede escribir fácilmente su propio código. Te daré un fragmento de uno de mis proyectos.

public void SaveLogFile(object method, Exception exception)
{
    string location = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\FolderName\";
    try
    {
        //Opens a new file stream which allows asynchronous reading and writing
        using (StreamWriter sw = new StreamWriter(new FileStream(location + @"log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
        {
            //Writes the method name with the exception and writes the exception underneath
            sw.WriteLine(String.Format("{0} ({1}) - Method: {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), method.ToString()));
            sw.WriteLine(exception.ToString()); sw.WriteLine("");
        }
    }
    catch (IOException)
    {
        if (!File.Exists(location + @"log.txt"))
        {
            File.Create(location + @"log.txt");
        }
    }
}

Luego, para escribir realmente en el registro de errores, simplemente escriba (q siendo la excepción capturada)

SaveLogFile(MethodBase.GetCurrentMethod(), `q`);
 4
Author: MisdartedPenguin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-17 07:44:17

Yo sugeriría "Postsharp". Da un marco muy elegante para implementar el registro sin modificar ninguna lógica de negocio.

 1
Author: Siva Sankar Gorantla,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-20 05:50:41