当前位置:  开发笔记 > 前端 > 正文

Silverlight日志记录框架和/或最佳实践

如何解决《Silverlight日志记录框架和/或最佳实践》经验,为你挑选了2个好方法。

现在Silverlight 2终于出货了.我想知道是否有人为它设置了任何日志框架,可能是企业库日志或log4net?我很有兴趣可以执行跟踪客户端并将消息记录到服务器.

到目前为止,我已经找到了唯一的项目是堵塞在CodeProject上.有没有人用过这个?你对此有何看法?



1> Chris S..:

如果您愿意将宇航员的头盔关闭一分钟,下面是我为Silverlight编写的轻量级记录器,用于客户端日志记录(主要用于WCF操作,但可能用于任何错误).

它最初用于iPhone应用程序的Monotouch,并已适应IsolateStorage.Read如果需要,您可以使用该方法在文本框中显示.在SL4中测试过.

/// 
/// A lightweight logging class for Silverlight.
/// 
public class Log
{
    /// 
    /// The log file to write to. Defaults to "dd-mm-yyyy.log" e.g. "13-01-2010.log"
    /// 
    public static string LogFilename { get; set; }

    /// 
    /// Whether to appendthe calling method to the start of the log line.
    /// 
    public static bool UseStackFrame { get; set; }

    static Log()
    {
        LogFilename = string.Format("{0}.log", DateTime.Today.ToString("dd-MM-yyyy"));
        UseStackFrame = false;
    }

    /// 
    /// Reads the entire log file, or returns an empty string if it doesn't exist yet.
    /// 
    /// 
    public static string ReadLog()
    {
        string result = "";
        IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForSite();

        if (storage.FileExists(LogFilename))
        {
            try
            {
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(LogFilename,FileMode.OpenOrCreate,storage))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        result = reader.ReadToEnd();
                    }
                }
            }
            catch (IOException)
            {
                // Ignore
            }
        }

        return result;
    }

    /// 
    /// Writes information (not errors) to the log file.
    /// 
    /// A format string
    /// Any arguments for the format string.
    public static void Info(string format, params object[] args)
    {
        WriteLine(LoggingLevel.Info, format, args);
    }

    /// 
    /// Writes a warning (non critical error) to the log file
    /// 
    /// A format string
    /// Any arguments for the format string.
    public static void Warn(string format, params object[] args)
    {
        WriteLine(LoggingLevel.Warn, format, args);
    }

    /// 
    /// Writes a critical or fatal error to the log file.
    /// 
    /// A format string
    /// Any arguments for the format string.
    public static void Fatal(string format, params object[] args)
    {
        WriteLine(LoggingLevel.Fatal, format, args);
    }

    /// 
    /// Writes the args to the default logging output using the format provided.
    /// 
    public static void WriteLine(LoggingLevel level, string format, params object[] args)
    {
        string message = string.Format(format, args);

        // Optionally show the calling method
        if (UseStackFrame)
        {
            var name = new StackFrame(2, false).GetMethod().Name;

            string prefix = string.Format("[{0} - {1}] ", level, name);
            message = string.Format(prefix + format, args);
        }

        Debug.WriteLine(message);
        WriteToFile(message);
    }

    /// 
    /// Writes a line to the current log file.
    /// 
    /// 
    private static void WriteToFile(string message)
    {
        try
        {
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForSite();
            bool b = storage.FileExists(LogFilename);

            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(LogFilename,FileMode.Append,storage))
            {
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.WriteLine("[{0}] {1}", DateTime.UtcNow.ToString(), message);
                }
            }
        }
        catch (IOException)
        {
            // throw new Catch22Exception();
        }
    }
}

/// 
/// The type of error to log.
/// 
public enum LoggingLevel
{
    /// 
    /// A message containing information only.
    /// 
    Info,
    /// 
    /// A non-critical warning error message.
    /// 
    Warn,
    /// 
    /// A fatal error message.
    /// 
    Fatal
}



2> Rene Schulte..:

如果您只想将调试消息输出到控制台.您可以使用浏览器的console.log机制.我编写了一个扩展方法.你可以在我的博客上找到.

    // http://kodierer.blogspot.com.es/2009/05/silverlight-logging-extension-method.html
    public static string Log(string message)
    {
        var msgLog = "";
        try
        {

            HtmlWindow window = HtmlPage.Window;

            //only log if a console is available
            var isConsoleAvailable = (bool)window.Eval("typeof(console) != 'undefined' && typeof(console.log) != 'undefined'");

            if (!isConsoleAvailable) return "isConsoleAvailable " + isConsoleAvailable;

            var createLogFunction = (bool)window.Eval("typeof(ssplog) == 'undefined'");
            if (createLogFunction)
            {
                // Load the logging function into global scope:
                string logFunction = @"function ssplog(msg) { console.log(msg); }";
                string code = string.Format(@"if(window.execScript) {{ window.execScript('{0}'); }} else {{ eval.call(null, '{0}'); }}", logFunction);
                window.Eval(code);
            }

            // Prepare the message
            DateTime dateTime = DateTime.Now;
            string output = string.Format("{0} - {1} - {2}", dateTime.ToString("u"), "DEBUG", message);

            // Invoke the logging function:
            var logger = window.Eval("ssplog") as ScriptObject;
            logger.InvokeSelf(output);
        }
        catch (Exception ex)
        {
            msgLog = "Error Log " + ex.Message;
        }
        return msgLog;

    }

推荐阅读
郑小蒜9299_941611_G
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有