Tag Archive for logging

Snippet of Log,Logfactory declaration in class

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

    	/**
	 * Logging facilities provided by Apache Commons Logging. When using log4j,
	 * logging facilities are configured in the {@code log4j.properties} file,
	 * which must be in the {@code CLASSPATH}.
	 */
	private static final Log logger =
			LogFactory.getLog(CLASSNAME_HERE.class);

source

Log4r: how to use RollingFileOutputter: automatically cycle stale logfiles

# How to use RollingFileOutputter 

$: << "../src"

require 'log4r'

include Log4r 

puts "this will take a while" 

# example of log file being split by time constraint 'maxtime'

config = {

  "filename" => "logs/TestTime.log",

  "maxtime" => 10,

  "trunc" => true

}

timeLog = Logger.new 'WbExplorer'

timeLog.outputters = RollingFileOutputter.new("WbExplorer", config)

timeLog.level = DEBUG 

# log something once a second for 100 seconds

100.times { |t|

  timeLog.info "blah #{t}"

  sleep(1.0)

} 

# example of log file being split by space constraint 'maxsize'

config = {

  "filename" => "logs/TestSize.log",

  "maxsize" => 16000,

  "trunc" => true

}

sizeLog = Logger.new 'WbExplorer'

sizeLog.outputters = RollingFileOutputter.new("WbExplorer", config)

sizeLog.level = DEBUG 

# log a large number of times

100000.times { |t|

  sizeLog.info "blah #{t}"

} 

puts "done! check the two sets of log files in logs/ (TestTime and TestSize)"

source

Get the Namespace, Class Name, and Method Name of the Currently Executing Method Via Reflection

protected string Source
  {
    get
    {
      StackTrace st = new StackTrace(true);
      MethodBase mb = st.GetFrame(1).GetMethod(); 
      return mb.ReflectedType.Namespace + "." + mb.ReflectedType.Name + "." + mb.Name; 
    }
  }

//Use like so: 
  public void DoChildStuff()
  {            
    Log(Source, "Doing Child Stuff");
  }

source

Logging in .NET with NLog (default config file, catch all exceptions and route to logger, …)

[app.config]
<?xml version="1.0"?>
<configuration>
    <configSections>
		<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
	</configSections>

	<nlog xmlns="<a href="http://www.nlog-project.org/schemas/NLog.xsd"" >http://www.nlog-project.org/schemas/NLog.xsd"</a> xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">" >http://www.w3.org/2001/XMLSchema-instance"></a>
		<variable name="appTitle" value="My Application"/>
		<variable name="logFilePath" value="${specialfolder:folder=Desktop:file=${appTitle} log.log}"/>

		<targets async="true">
			<target name="file" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message}${newline}(${stacktrace}) ${exception:format=ToString}"/>
			
			<target name="fileAsInfo" xsi:type="File" fileName="${logFilePath}" layout="${longdate} ${level:upperCase=true}: ${message} ${exception:format=ToString}"/>
			
			<target xsi:type="EventLog" name="eventLog" source="${appTitle}" layout="${message}${newline}${exception:format=tostring}"/>
		</targets>
		
		<targets>
			<target xsi:type="MessageBox" name="mbox" caption="Error" layout="An error has occurred. Please see the log file (${logFilePath}) or event log for more details."/>
		</targets>

		<rules>
			<logger name="*" level="Info" writeTo="fileAsInfo"/>
			<logger name="*" minlevel="Warn" writeTo="file"/>
			<logger name="*" minlevel="Warn" writeTo="eventLog"/>
			<logger name="*" minlevel="Error" writeTo="mbox"/>
		</rules>
	</nlog>
</configuration>

// WinForms App
static class Program
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += OnThreadException;
        AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            Application.Run(new PrimaryForm());
        }
        catch (Exception exc)
        {
            LogFatalException(exc);
            throw;
        }
    }

    private static void LogFatalException(Exception exc)
    {
        string message = String.Format(
            "(Application version {0}) {1}", Application.ProductVersion, exc.Message);

        _logger.FatalException(message, exc);
        Application.Exit(); // Encouraged, but not required
    }

    private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
            if (e.IsTerminating)
            {
                _logger.Info("Application is terminating due to an unhandled exception in a secondary thread.");
            }
        LogFatalException(e.ExceptionObject as Exception);
    }

    private static void OnThreadException(object sender, ThreadExceptionEventArgs e)
    {
        LogFatalException(e.Exception);
    }
}

// WPF App
// App.xaml:
<Application x:Class="UI.App"
    xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation"" >http://schemas.microsoft.com/winfx/2006/xaml/presentation"</a>
    xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml"" >http://schemas.microsoft.com/winfx/2006/xaml"</a>
    DispatcherUnhandledException="Application_DispatcherUnhandledException"
    Startup="Application_Startup"
    StartupUri="UserInterface.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

// App.xaml.cs
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    private readonly Logger _logger = LogManager.GetLogger("App");

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        // UI Exceptions
        this.DispatcherUnhandledException += Application_DispatcherUnhandledException;

        // Thread exceptions
        AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
    }

    private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        e.Handled = true;
        var exception = e.Exception;
        HandleUnhandledException(exception);
    }
    
    private void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
    {
        HandleUnhandledException(unhandledExceptionEventArgs.ExceptionObject as Exception);
        if (unhandledExceptionEventArgs.IsTerminating)
        {
            _logger.Info("Application is terminating due to an unhandled exception in a secondary thread.");
        }
    }

    private void HandleUnhandledException(Exception exception)
    {
        string message = "Unhandled exception";
        try
        {
            AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
            message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
        }
        catch (Exception exc)
        {
            _logger.ErrorException("Exception in unhandled exception handler", exc);
        }
        finally
        {
            _logger.ErrorException(message, exception);
        }
    }
}

source

PHP Log to Text File

function doLog($text)
{
// open log file
$filename = "form_ipn.log";
$fh = fopen($filename, "a") or die("Could not open log file.");
fwrite($fh, date("d-m-Y, H:i")." - $text
") or die("Could not write file!");
fclose($fh);
}

source

Console Helper for Firebug

var put = function() { try{ console.log.apply(this,arguments); }catch(e){ alert(arguments); } };
function logAllMembers( obj ) {
for( var member in obj )
if ( obj[member] != null)
put(member + ' = ' + obj[member] + '
Argument(s) length: ' + obj[member].length +'
');
};

/*  use 'put' like this: put('this is a message that will appear in the console');

use 'logAllMembers' like this:
// make a class
FOO.insides = function (){};
FOO.insides.prototype = {

count:  10,
stub:   [],

methodOne: function(args){
return 'method one';
},

methodTwo: function(args, args2, args3){
return 'method two'
}
};
// create a new instance
bar = new FOO.insides();

bar.stub = ['apple','banana','pear','peach','apple'];

// look inside the instance
logAllMembers(bar);

// will return this:
stub = apple,banana,pear,peach,apple
Argument(s) length: 5
count = 10
Argument(s) length: undefined
methodOne = function (args) {
return "method one";
}
Argument(s) length: 1
methodTwo = function (args, args2, args3) {
return "method two";
}
Argument(s) length: 3

*/

source

intelligent logging

BASE = {
/**
* USAGE
* BASE.log(o)
* outputs the value of whatever is passed to it in either the firebug console,
* or a newly created window on top of your content;
* useful to debug various problems within your scripts
* @param o = any object, array, number, or string
*/
log:function(o)
{
var logger = (this.isObject(window.console) && window.console.firebug) || null;
if(!logger){
if(document.createElement && document.getElementById){
var elem = document.createElement('div') || document.getElementById('logger'),
p = document.createElement('pre') || elem.firstChild,
t = null, d = document.getElementsByTagName('body')[0],
r = null, res = 'no data passed
', opac = 20, that = this;

if(this.isObject(o) && !this.isArray(o)){
r = [];
for(var i in o){
var name = o.nodeName || o.toString();
r.push(name + '.' + i + '=' + o[i] + '
');
}
r.sort();
res = r.join('
') || 'empty object
';
}
else if(this.isArray(o)){
r = [];
for(var i in o){
var name = o.nodeName || o.toString();
r.push(i + '=' + o[i] + '
');
}
r.sort();
res = r.join('
') || 'empty array
';
}
else if(this.isString(o)){
res = o + '
' || 'no string to display
';
}
else if(this.isNumber(o)){
res = o + '
' || 'no number to display
';
};
if(!document.getElementById('logger')){
t = document.createTextNode(res);
p.appendChild(t); elem.appendChild(p);
//required styles
elem.id = 'logger'; elem.className = 'console-window';
elem.style['overflow'] = 'auto'; elem.style['top'] = '0px'; elem.style['zIndex'] = '1000';
elem.style['left'] = '25%'; elem.style['width'] = '50%'; elem.style['margin'] = '10px auto';
elem.style['position'] = 'fixed';
if(this.isIE){
elem.style['position'] = 'absolute';
document.body.style['overflowY'] = 'auto';
document.body.style['height'] = '100%'
}
p.style.className = 'window-text'; p.style['whiteSpace'] = 'pre'; p.style['textAlign'] = 'left';
//default styles can be overridden using !important declarations in style sheets
elem.style['padding'] = '5px 20px'; elem.style['height'] = '250px'; elem.style['backgroundColor'] = '#ffffff';
elem.style['border'] = '1px solid red';
//add transparency
this.setOpacity(opac, elem);
elem.onmouseover = function(){
that.setOpacity(100, elem);
//this.style['position'] = 'fixed';
};
elem.onmouseout = function(){
that.setOpacity(opac, elem);
//this.style['position'] = 'absolute';
};
//return new node to add to DOM
return d.insertBefore(elem, d.firstChild);
}
else {
return document.getElementById('logger').firstChild.firstChild.nodeValue += res;
}
}
else {
window.alert('you should probably upgrade your browser!');
}
}
else {
if(this.isObject(o)){
console.dir(o);
}
else {
console.log(o);
}
}
},
isArray: function(object){
return object !== null && typeof object == "object" &&
'splice' in object && 'join' in object;
},
isFunction: function(object){
return typeof object == "function";
},
isObject: function(object){
return (object && (typeof object === 'object' || this.isFunction(object))) || false;
},
isString: function(object){
return typeof object == "string";
},
isNumber: function(object){
return typeof object == "number";
},
isIE:function()
{
return !!( (/(msie 6|msie 7)/i).test(navigator.userAgent) && !(/opera/i).test(navigator.userAgent.indexOf('opera')) && window.ActiveXObject );
}(),
setOpacity:function(opacity, element)
{
if(!element.style['zoom']) {
//correct hasLayout IE transparency
element.style['zoom'] = 1;
};
if(element.style['MozOpacity']) {
element.style['MozOpacity'] = (opacity / 100);
};
if(element.style['KhtmlOpacity']) {
element.style['KhtmlOpacity'] = (opacity / 100);
};
if(element.filters) {
element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(Opacity=' + opacity + ')';
element.style.filter = 'alpha(opacity=' + Math.round(opacity) + ')';
};
element.style['opacity'] = (opacity / 100);
}
};

source

Logging in Firebug

console.log(variable);

source

Logging from inside a rails model

RAILS_DEFAULT_LOGGER.error

source

List commands in history, sorted by usage

history  | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head

# Full sousveillance version:
history | awk '{a[$2 " " $3 " " $4 " " $5]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head -n+25

source