using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
namespace Eugen.ESystem.IO
{
public class LogWriter
{
#region Version und Copyright
// Version und Copyright
static string dllName = System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase); //Den Programmnamen auslesen
static string dllVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
static object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
static string copyright = GenerateCopyright();
//Assembly Datum und Zeit
static DateTime value = AssemblyDateTime();
static string date = value.ToShortDateString();
static string time = value.ToLongTimeString();
private static DateTime AssemblyDateTime()
{
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
var buildDateTime = new DateTime(2000, 1, 1).Add(new TimeSpan(TimeSpan.TicksPerDay * version.Build + TimeSpan.TicksPerSecond * 2 * version.Revision));
//Tage seit dem 1. Januar 2000 und Sekunden seit Mitternacht, (multiplizier mit 2 ergibt das Original)
return buildDateTime;
}
private static string CurrentYear()
{
DateTime dtn = DateTime.Now;
return dtn.Year.ToString();
}
private static string StartYear()
{
string startYear = "";
if (((AssemblyCopyrightAttribute)attributes[0]).Copyright.Contains("Copyright © "))
{
startYear = ((AssemblyCopyrightAttribute)attributes[0]).Copyright.Replace("Copyright © ", "");
while (startYear.StartsWith(" "))
{
startYear = startYear.Remove(0, 1);
}
if (startYear.Contains("-"))
{
startYear = startYear.Remove(startYear.IndexOf("-"));
}
else
{
startYear = startYear.Remove(startYear.IndexOf(" "));
}
return startYear;
}
else
{
DateTime dtn = DateTime.Now;
return dtn.Year.ToString();
}
}
private static string GenerateCopyright()
{
string startYear = StartYear();
string currentYear = CurrentYear();
if (startYear == currentYear)
{
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
else
{
string temp = ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
string start = temp.Remove(temp.IndexOf(startYear) - 1);
string end = (temp.Remove(0, temp.IndexOf(" by")));
return String.Concat(start, " ", startYear, "-", currentYear, end);
}
}
#endregion
#region DLL-Info
///
/// Contains the name of the dll file.
///
public static string DllName { private set; get; }
///
/// Contains the version of the dll file.
///
public static string DllVersion { private set; get; }
///
/// Contains the copyright notice.
///
public static string Copyright { private set; get; }
///
/// Contains the name-, version- and copyright-information of the dll file.
///
public static string[] DllInfo { private set; get; }
private static void SetDllInfo()
{
//Name, Version und Copyright setzen
DllName = dllName;
DllVersion = dllVersion;
Copyright = copyright;
string[] dllInfo = new string[3];
dllInfo[0] = dllName;
dllInfo[1] = dllVersion;
dllInfo[2] = copyright;
DllInfo = dllInfo;
}
protected string ProgramName { private set; get; }
protected string ProgramVersion { private set; get; }
protected string ProgramCopyright { private set; get; }
#endregion
public enum Time
{
Write,
NoWrite
}
public enum LogLevel
{
Information,
Warning,
Error,
Fatal,
NoWrite
}
static LogWriter()
{
SetDllInfo();
}
public LogWriter(string path)
{
SetDllInfo();
SetDate();
this.Path = path;
this.FileName = String.Concat("log_", this.CurrentDate, ".log");
}
public LogWriter(string path, string fileName)
{
SetDllInfo();
SetDate();
this.Path = path;
if (fileName.EndsWith(".log"))
{
this.FileName = fileName;
}
else
{
this.FileName = String.Concat(fileName, ".log");
}
}
private string Path { get; set; }
private string FileName { get; set; }
private string CurrentDate { get; set; }
private string MessageFormat
{
get
{
return this.messageFormat;
}
set
{
this.messageFormat = value;
}
}
private void SetDate()
{
DateTime dateTime = DateTime.Now;
this.CurrentDate = dateTime.ToString().Remove(dateTime.ToString().IndexOf(" "));
}
private string messageFormat = "{0}{1:T}.{2} - {3}"; // Definiert das Mitteilungsformat
///
/// Writes a message to a log file
///
/// The message to write
/// On success true is returned, on the other hand false
public bool WriteMessage(string message)
{
return WriteMessage(message, LogLevel.NoWrite, Time.Write);
}
///
/// Writes a message to a log file
///
/// The message to write
/// Writes the log level in front of the line
/// Writes the log time
/// On success true is returned, on the other hand false
public bool WriteMessage(string message, LogLevel writeLogLevel, Time writeTime)
{
string logLevel = "";
switch (writeLogLevel)
{
case LogLevel.Information:
logLevel = "INFO - ";
break;
case LogLevel.Warning:
logLevel = "WARN - ";
break;
case LogLevel.Error:
logLevel = "ERROR - ";
break;
case LogLevel.Fatal:
logLevel = "FATAL - ";
break;
case LogLevel.NoWrite:
logLevel = "";
break;
default:
logLevel = "";
break;
}
DateTime time = DateTime.Now;
int ms = time.Millisecond;
if (writeTime == Time.Write)
{
return WriteLine(logLevel, time, ms, String.Format(this.messageFormat, new object[] { logLevel, time, ms.ToString("000"), message }));
}
else
{
return WriteLine(logLevel, time, ms, message);
}
}
private bool WriteLine(string logLevel, DateTime time, int ms, string message)
{
try
{
StreamWriter writer;
if (!File.Exists(String.Concat(this.Path, "\\", this.FileName)))
{
// Wenn Logdatei noch nicht existiert, dann anlegen
writer = new StreamWriter(String.Concat(this.Path, "\\", this.FileName));
OnFileCreated(EventArgs.Empty);
}
else
{
// Wenn Logdatei schon nicht existiert, dann zum Schreiben öffnen
writer = new StreamWriter(String.Concat(this.Path, "\\", this.FileName), true);
}
// Zeile schreiben
writer.WriteLine(message);
// Logdatei schließen
writer.Close();
OnMessageWritten(new LogWriterEventArgs(logLevel, time, ms, message));
return true;
}
catch (Exception)
{
return false;
}
}
///
/// Displays the current logfile
///
/// Wheather the displaying progress was successful
public bool ShowLogFile()
{
return ShowLogFile(this.Path, this.FileName);
}
/////
///// Displays a logfile
/////
///// A valid path
///// A valid filename
///// Wheather the displaying progress was successful
//public bool ShowLogFile(string path, string fileName)
//{
// if (String.IsNullOrEmpty(path) || String.IsNullOrEmpty(fileName))
// {
// return false; // Pfad oder Name wurde nicht gefunden
// }
// else
// {
// if (!fileName.EndsWith(".log"))
// {
// fileName = String.Concat(fileName, ".log");
// }
// if (File.Exists(String.Concat(path, "\\", fileName)))
// {
// if (!ShowTextFile.Show(String.Concat(path, "\\", fileName)))
// {
// return false; // Editor nicht gefunden
// }
// }
// else
// {
// return false; //Datei nicht gefunden
// }
// }
// return true;
//}
///
/// Displays a logfile
///
/// A valid path
/// A valid filename
/// Wheather the displaying progress was successful
public bool ShowLogFile(string path, string fileName)
{
if (String.IsNullOrEmpty(path) || String.IsNullOrEmpty(fileName))
{
return false; // Pfad oder Name wurde nicht gefunden
}
else
{
if (File.Exists(String.Concat(path, "\\", fileName)))
{
try
{
//Aufruf mit dem Standardprogramm
var process = new Process();
process.StartInfo = new ProcessStartInfo()
{
UseShellExecute = true,
FileName = String.Concat(path, "\\", fileName)
};
process.Start();
process.WaitForExit();
return true;
}
catch (Exception)
{
try
{
const string program = "Notepad.exe"; //Aufruf mit Notepad
ProcessStartInfo start = new ProcessStartInfo(program, String.Concat(path, "\\", fileName));
Process.Start(start);
return true;
}
catch (Exception)
{
return false;
}
}
}
else
{
return false;
}
}
}
///
/// Deletes the current Logfile
///
/// Wheather the deleting progress was successful
public bool Delete()
{
try
{
if (String.IsNullOrEmpty(Path) || String.IsNullOrEmpty(FileName))
{
return false;
}
if (!File.Exists(String.Concat(this.Path, "\\", this.FileName)))
{
return true; // Existiert nicht mehr
}
else
{
// Muss noch gelöscht werden
File.Delete(String.Concat(this.Path, "\\", this.FileName));
if (File.Exists(String.Concat(this.Path, "\\", this.FileName)))
{
return false; // Konnte nicht gelöscht werden
}
else
{
return true; // Wurde erfolgreich gelöscht
}
}
}
catch (Exception)
{
return false;
}
}
public bool Delete(string path, string fileName)
{
if (!fileName.EndsWith(".log"))
{
fileName = String.Concat(fileName, ".log");
}
try
{
if (File.Exists(String.Concat(path, "\\", fileName)))
{
File.Delete(String.Concat(path, "\\", fileName));
if (File.Exists(String.Concat(path, "\\", fileName)))
{
return false; // Konnte nicht gelöscht werden
}
else
{
return true; // Wurde erfolgreich gelöscht
}
}
else
{
return true; // Existiert nicht mehr
}
}
catch (Exception)
{
return false;
}
}
///
/// Provides a method, wich handles events from written messages
///
/// Sender object
/// Event arguments
public delegate void LogWriterEventHandler(object sender, LogWriterEventArgs e);
///
/// Fires the FileCreated event
///
/// Event arguments
protected void OnFileCreated(EventArgs e)
{
if (FileCreated != null)
{
FileCreated(this, e);
}
}
///
/// Fires the MessageWritten event
///
/// Event arguments
protected void OnMessageWritten(LogWriterEventArgs e)
{
if (MessageWritten != null)
{
MessageWritten(this, e);
}
}
///
/// Fired, when a new log file was created. Fired, when a message was written
///
public event EventHandler FileCreated;
///
/// Fired, when a message was written
///
public event LogWriterEventHandler MessageWritten;
}
///
/// LogWriterEventArgs stores information about the sent log message
///
public class LogWriterEventArgs : EventArgs
{
///
/// Constructor
///
/// Specifyes the message post time
/// Specifyes the message post milliseconds
/// Specifyes the message
public LogWriterEventArgs(string logLevel, DateTime time, int millisecond, string message) : base()
{
this.logLevel = logLevel;
this.time = time;
this.millisecond = millisecond;
this.message = message;
}
#region fields
///
/// Stores the logging level
///
private string logLevel;
///
/// Stores the message post time
///
private DateTime time;
///
/// Stores the milliseconds of the post time of the message
///
private int millisecond;
///
/// Stores the message
///
private string message;
#endregion
#region properties
///
/// Specifyes the message post time
///
public DateTime Time
{
get
{
return this.time;
}
}
///
/// Specifyes the message
///
public string Message
{
get
{
return this.message;
}
}
#endregion
}
}