www.pudn.com > Fetion.rar > ImpsLogger.cs
namespace Imps.Client.Logger
{
using Imps.Client.Base;
using Imps.Client.Core;
using Imps.Client.Pc;
using Imps.Client.Utils;
using Imps.Utils;
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
public class ImpsLogger : IImpsLogger
{
private volatile bool _CreateNewLogFile = true;
private Regex _ExtRegex = new Regex(@"(.*?) ", RegexOptions.Compiled | RegexOptions.Multiline);
private IFrameworkWindow _host;
private bool _IsLogBiz = true;
private bool _IsLogConnection = true;
private bool _IsLogException = true;
private bool _IsLogGeneral = true;
private bool _IsLogInstall = true;
private bool _IsLogLiveUpdate = true;
private bool _IsLogLogin = true;
private bool _IsLogSipc = true;
private string _LogFile;
private Hashtable _LogFileNames = new Hashtable();
private string _LogFolder;
private Imps.Client.Logger.LogHeader _LogHeader = new Imps.Client.Logger.LogHeader();
private Imps.Client.Utils.LogType _LogType = (Imps.Client.Utils.LogType.SingleFile | Imps.Client.Utils.LogType.GlobalFile);
private int _MaxLogNo = 9;
private static string _processId = string.Empty;
private string _ServerUrl = string.Empty;
private int _ThresholdLevel;
private const string FileName = "Imps";
private const int PostMaxSize = 0x800;
public ImpsLogger(IFrameworkWindow host)
{
this._host = host;
this.LogHeader.TimeStamp = DateTime.Now;
this.LogHeader.Version = "1.0";
this.LogHeader.MachineEnv.OS = Environment.OSVersion.ToString();
this.LogHeader.MachineEnv.Language = CultureInfo.CurrentCulture.Name;
this.LogHeader.MachineEnv.IE = string.Empty;
this.LogHeader.MachineEnv.MemorySize = GetMemorySize();
this.LogHeader.MachineEnv.VideoCard = GetVideoCard();
}
private string CombineFileName(int no)
{
return Path.Combine(this.LogFolder, "Imps." + no.ToString("000") + ".log");
}
public void CreateLogFile()
{
if (this._CreateNewLogFile)
{
if (!Directory.Exists(this.LogFolder))
{
Directory.CreateDirectory(this.LogFolder);
}
string str = string.Empty;
for (int i = 1; i <= this.MaxLogNo; i++)
{
if (!System.IO.File.Exists(str = this.CombineFileName(i)))
{
break;
}
str = string.Empty;
}
if (string.IsNullOrEmpty(str))
{
for (int j = 2; j <= this.MaxLogNo; j++)
{
string path = this.CombineFileName(j);
string str3 = this.CombineFileName(j - 1);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(str3);
System.IO.File.Move(path, str3);
}
}
str = this.CombineFileName(this.MaxLogNo);
}
using (StreamWriter writer = new StreamWriter(str, false, Encoding.UTF8))
{
writer.WriteLine(this.LogHeader.ToString());
}
this._CreateNewLogFile = false;
this._LogFile = str;
}
}
private string GetLogFileNameByCategory(string category)
{
category = category.ToLower();
if (!this._LogFileNames.ContainsKey(category))
{
string path = Path.Combine(this.LogFolder, category + ".log");
using (StreamWriter writer = new StreamWriter(path, false, Encoding.UTF8))
{
writer.WriteLine(this.LogHeader.ToString());
}
this._LogFileNames.Add(category, path);
}
return (this._LogFileNames[category] as string);
}
private static uint GetMemorySize()
{
MEMORY_INFO meminfo = new MEMORY_INFO();
GlobalMemoryStatus(ref meminfo);
return meminfo.dwTotalPhys;
}
private static string GetVideoCard()
{
return string.Empty;
}
[DllImport("kernel32")]
private static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo);
private bool IsLog(string category, int infoLevel)
{
if ((this._host != null) && (this._host.AccountManager != null))
{
User currentUser = this._host.AccountManager.CurrentUser;
if ((currentUser != null) && currentUser.Configuration.SystemSetting.RecordMyLog)
{
return true;
}
}
if (infoLevel >= this.ThresholdLevel)
{
switch (category)
{
case "General":
return this.IsLogGeneral;
case "Biz":
return this.IsLogBiz;
case "Connection":
return this.IsLogConnection;
case "LogIn":
return this.IsLogLogin;
case "Sipc":
return this.IsLogSipc;
case "Exception":
return this.IsLogException;
}
}
return false;
}
private bool IsNeedCallStack(string category, int level)
{
bool flag = level >= 20;
string str = category;
if (str == null)
{
return flag;
}
if (!(str == "Exception"))
{
if (str == "Sipc")
{
return false;
}
return flag;
}
return true;
}
private void PostFile(ImpsLoggerSender sender, string logFile)
{
if (System.IO.File.Exists(logFile))
{
byte[] buffer = new byte[0x800];
using (FileStream stream = new FileStream(logFile, FileMode.Open))
{
int num;
while ((num = stream.Read(buffer, 0, buffer.Length)) > 0)
{
sender.Post(buffer, 0, num);
}
}
}
}
public void SendToServer(Imps.Client.Utils.LogType logType)
{
if (logType != Imps.Client.Utils.LogType.None)
{
if (string.IsNullOrEmpty(this.ServerUrl))
{
throw new ApplicationException("未指定服务器URL");
}
ImpsLoggerSender sender = new ImpsLoggerSender(this._ServerUrl);
sender.Post(this.LogHeader.ToArray());
if ((logType | Imps.Client.Utils.LogType.GlobalFile) != Imps.Client.Utils.LogType.None)
{
this.PostFile(sender, this._LogFile);
}
if ((logType | Imps.Client.Utils.LogType.SingleFile) != Imps.Client.Utils.LogType.None)
{
foreach (string str in this._LogFileNames.Values)
{
this.PostFile(sender, str);
}
}
sender.PostEnd();
}
}
private string TrimValue(string value)
{
if (value.Length > 1)
{
if ((value[0] == '"') && (value[value.Length - 1] == '"'))
{
return value.Substring(1, value.Length - 2);
}
if ((value[0] == '\'') && (value[value.Length - 1] == '\''))
{
return value.Substring(1, value.Length - 2);
}
}
return value;
}
public void WriteLine(string category, int infoLevel, string summary, string detail, string ext)
{
if (this.IsLog(category, infoLevel))
{
try
{
if (this._CreateNewLogFile && ((this.LogType & Imps.Client.Utils.LogType.GlobalFile) != Imps.Client.Utils.LogType.None))
{
this.CreateLogFile();
}
if (this.LogType != Imps.Client.Utils.LogType.None)
{
MemoryStream w = new MemoryStream();
using (XmlTextWriter writer = new XmlTextWriter(w, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartElement("Record");
writer.WriteAttributeString("pid", CurrentProcessId);
writer.WriteAttributeString("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
writer.WriteAttributeString("level", infoLevel.ToString());
writer.WriteAttributeString("category", category);
writer.WriteStartElement("Summary");
writer.WriteString(summary);
writer.WriteEndElement();
writer.WriteStartElement("Detail");
if (detail.IndexOfAny("<>".ToCharArray()) >= 0)
{
writer.WriteCData(detail.Replace("]]>", "?]>"));
}
else
{
writer.WriteString(detail);
}
writer.WriteEndElement();
writer.WriteStartElement("CallStack");
writer.WriteCData(this.IsNeedCallStack(category, infoLevel) ? DebugHelper.GetCallStackString(1) : string.Empty);
writer.WriteEndElement();
writer.WriteStartElement("ExtData");
if (!string.IsNullOrEmpty(ext))
{
System.Text.RegularExpressions.Match match = this._ExtRegex.Match(ext);
if (match.Success)
{
foreach (System.Text.RegularExpressions.Match match2 in Regex.Matches(match.Groups[1].Value, @"(\S+?)\s*=\s*(\S+)", RegexOptions.Multiline))
{
writer.WriteAttributeString(match2.Groups[1].Value, this.TrimValue(match2.Groups[2].Value));
}
writer.WriteCData(match.Groups[2].Value);
}
else
{
writer.WriteCData(ext);
}
}
writer.WriteEndElement();
writer.WriteEndElement();
writer.Flush();
byte[] bytes = Encoding.UTF8.GetBytes("\r\n");
w.Write(bytes, 0, bytes.Length);
}
lock (this._LogFile)
{
string contents = Encoding.UTF8.GetString(w.ToArray());
if ((this.LogType | Imps.Client.Utils.LogType.GlobalFile) != Imps.Client.Utils.LogType.None)
{
System.IO.File.AppendAllText(this._LogFile, contents, Encoding.UTF8);
}
if ((this.LogType | Imps.Client.Utils.LogType.SingleFile) != Imps.Client.Utils.LogType.None)
{
System.IO.File.AppendAllText(this.GetLogFileNameByCategory(category), contents, Encoding.UTF8);
}
}
}
}
catch
{
}
}
}
private static string CurrentProcessId
{
get
{
if (string.IsNullOrEmpty(_processId))
{
_processId = Process.GetCurrentProcess().Id.ToString();
}
return _processId;
}
}
public bool IsLogBiz
{
get
{
return this._IsLogBiz;
}
set
{
this._IsLogBiz = value;
}
}
public bool IsLogConnection
{
get
{
return this._IsLogConnection;
}
set
{
this._IsLogConnection = value;
}
}
public bool IsLogException
{
get
{
return this._IsLogException;
}
set
{
this._IsLogException = value;
}
}
public bool IsLogGeneral
{
get
{
return this._IsLogGeneral;
}
set
{
this._IsLogGeneral = value;
}
}
public bool IsLogInstall
{
get
{
return this._IsLogInstall;
}
set
{
this._IsLogInstall = value;
}
}
public bool IsLogLiveUpdate
{
get
{
return this._IsLogLiveUpdate;
}
set
{
this._IsLogLiveUpdate = value;
}
}
public bool IsLogLogin
{
get
{
return this._IsLogLogin;
}
set
{
this._IsLogLogin = value;
}
}
public bool IsLogSipc
{
get
{
return this._IsLogSipc;
}
set
{
this._IsLogSipc = value;
}
}
public string LogFolder
{
get
{
return this._LogFolder;
}
set
{
this._LogFolder = value;
}
}
public Imps.Client.Logger.LogHeader LogHeader
{
get
{
return this._LogHeader;
}
}
public Imps.Client.Utils.LogType LogType
{
get
{
return this._LogType;
}
set
{
this._LogType = value;
}
}
public int MaxLogNo
{
get
{
return this._MaxLogNo;
}
set
{
if ((value <= 0) || (value > 100))
{
throw new ArgumentException("最大文件号必须在1-100范围之内");
}
this._MaxLogNo = value;
}
}
public string ServerUrl
{
get
{
return this._ServerUrl;
}
set
{
this._ServerUrl = value;
}
}
public int ThresholdLevel
{
get
{
return this._ThresholdLevel;
}
set
{
this._ThresholdLevel = value;
}
}
private class ImpsLoggerSender
{
private string _ServerUrl;
private CookieContainer cookie = new CookieContainer();
public ImpsLoggerSender(string serverUrl)
{
this._ServerUrl = serverUrl;
}
public void Post(byte[] buffer)
{
this.Post(buffer, 0, buffer.Length);
}
public void Post(byte[] buffer, int start, int length)
{
HttpWebRequest request = ConnectionFactory.CreateHttpWebRequest(this._ServerUrl, null, true, true);
if (length != 0)
{
GZipStream stream = new GZipStream(request.GetRequestStream(), CompressionMode.Compress, false);
stream.Write(buffer, start, length);
stream.Close();
}
((HttpWebResponse) request.GetResponse()).Close();
}
public void PostEnd()
{
this.Post(new byte[0]);
}
}
[StructLayout(LayoutKind.Sequential)]
private struct MEMORY_INFO
{
public uint dwLength;
public uint dwMemoryLoad;
public uint dwTotalPhys;
public uint dwAvailPhys;
public uint dwTotalPageFile;
public uint dwAvailPageFile;
public uint dwTotalVirtual;
public uint dwAvailVirtual;
}
}
}