« powrót

Prosta klasa do przechowywania log'a wykonywanej aplikacji [C#]

Opublikowano: 2019-08-20 , wyświetlono: 2367

Kiedyś do testowania własnych aplikacji napisałem prostą klasę, która pozwalała mi przechowywać komunikaty i wyświetlać je w formacie tekstowym lub html.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ChinaSoftLibrary.Util
{
    public static class AppLog
    {
        private static List<string> _logData = new List<string>();

        public static void Clear()
        {
            _logData.Clear();
        }

        public static void Add(string message)
        {
            _logData.Add(message);
        }

        public static void Add(string title, string message)
        {
            _logData.Add(title + " : " + message);
        }
        public static void Add(string className, string method, string message)
        {
            _logData.Add(className + "::" + method + " : " + message);
        }

        public static void Add(Exception ex)
        {
            _logData.Add(ex.Message);
        }
        public static void Add(string title, Exception ex)
        {
            _logData.Add(title + " : " + ex.Message);
        }

        public static string GetText()
        {
            string txt = "";

            foreach (string s in _logData)
                txt += s + System.Environment.NewLine;

            return (txt);
        }
        public static string GetHtml()
        {
            string html = "";

            foreach (string s in _logData)
                html += s + "<br />" + System.Environment.NewLine;

            return (html);
        }
    }
}

Przykład zastosowania klasy w aplikacji konsolowej


AppLog.Clear();

AppLog.Add("rozpoczęcie testu");

try {
  result = 10.0 / 0;
}
catch (Exception ex) {
  AppLog.Add(ex);
}

AppLog.Add("koniec testu");

Console.WriteLine(AppLog.Gettext());



Komentarze: