Sign up to create your own snipts, or login.

Public snipts » log The latest public log snipts.

showing 1-20 of 21 snipts for log
  • VB6: Write a message in a daily log
    Public Sub WriteLog(Message As String)
    
      Dim fso, fileName As String, logString As String, f as Integer
      
      fileName = App.path & "\Log_" & Format(Now, "yyyymmdd") & ".txt"
      logString = Format(Now, "hh:mm:ss") & " - " & Message
      f = Freefile
      Open fileName For Append As #f
      Print #f, logString
      Close #f
    
    End Sub
    

    copy | embed

    0 comments - tagged in  posted by beccoblu on Feb 14, 2010 at 10:04 a.m. EST
  • Getting a logger with Log4j
    private static final Log LOG = LogFactory.getLog(SomeClassName.class);
    

    copy | embed

    0 comments - tagged in  posted by lenni on Feb 09, 2010 at 4:43 a.m. EST
  • view symfony log file
    $ tail -f log/frontend_dev.log
    

    copy | embed

    0 comments - tagged in  posted by toledot on Jan 28, 2010 at 5:30 p.m. EST
  • elapsed time between two log records
    #!/bin/bash
    
    #
    # parses the time (in seconds) that elapsed between 2 consecutive entries
    # each matching to pattern1 and pattern2.
    # date format : [DDD] [MMM] [dd] [hh]:[mm]:[ss] [YYYY]
    # example     : Tue May 12 06:49:44 2009
    #
    # substitute the patterns at will
    #
    # limitation : it works for entries having the same year
    #
    # example
    # Tue May 12 06:49:41 2009 - pattern1
    # Tue May 12 06:49:44 2009 - pattern2
    #
    # it should output :
    # 3
    #
    
    awk '
    BEGIN{
            m["Jan"]="01";
            m["Feb"]="02";
            m["Mar"]="03";
            m["Apr"]="04";
            m["May"]="05";
            m["Jun"]="06";
            m["Jul"]="07";
            m["Aug"]="08";
            m["Sep"]="09";
            m["Oct"]="10";
            m["Nov"]="11";
            m["Dec"]="12";
    
            d["Sun"]="01";
            d["Mon"]="02";
            d["Tue"]="03";
            d["Wed"]="04";
            d["Thu"]="05";
            d["Fri"]="06";
            d["Sat"]="07";
    
            s=0; # start timestamp
            e=0; # end timestamp
    }
    /pattern1/ {    dt1=$0; gsub(":"," ",$4);
                    spec1=sprintf("%s %s %s %s",$5,d[$1],m[$2],$4);
                    s=mktime(spec1); }
    /pattern2/ {
                    dt2=$0; gsub(":"," ",$4);
                    spec2=sprintf("%s %s %s %s",$5,d[$1],m[$2],$4);
                    e=mktime(spec2); print e-s; e=s=0; }' < $1
    

    copy | embed

    0 comments - tagged in  posted by cgv on Jan 28, 2010 at 8:52 a.m. EST
  • Perl API to generate a Log
    package uLog;
    
    use strict;
    use POSIX qw(uname strftime);
    use IO::File;
    # Next path is the place where MainConfig.pm is defined
    use lib '/aplicaciones/plataforma/spread/smsc';
    use MainConfig;
    
    use constant TRUE        => 1;
    use constant FALSE       => 0;
    
    eval "use Time::HiRes qw(gettimeofday)";
    my $HAS_TIME_HIRES = not $@;
    my $NODATAFIELD    = "-";
    my $DATEFORMAT     = "%F.%H:%m:%S.%Q";
    my $CFG = $MainConfig::CFG;
    my $DIRORDER = [ 
                     "$CFG->{paths}->{service_path}/logs/",
                     "./logs/",
                     "/tmp/" ];
    
    my $hrefLevels = {
            FAT => 1,
            ERR => 2,
            WAR => 3,
            INF => 4,
            DEB => 5,
            VER => 6
    };
    
    my $_LOGGER;
    
    sub _new {
            my ($args)  = @_;
    
            my (undef, $sHostname, undef, undef, undef) = uname();
            my $self = {
                    _sLogFile  => $NODATAFIELD,
                    _iLogLevel => $hrefLevels->{INF},
                    _sTicket   => $NODATAFIELD,
                    _sUser     => $ENV{USER} || $< || $NODATAFIELD,
                    _sService  => $NODATAFIELD,
                    _sMachine  => $sHostname || $NODATAFIELD,
                    _LOG_FH    => undef,
                    _iCounter  => 0,
                    _iDelta    => undef,
                    _iPID      => $$,
                    _sModule   => $NODATAFIELD
            };
            bless $self, 'uLog';
    
            $self->_init( $args );
            $_LOGGER = $self;
    
            return $self;
    }
    
    sub getLogger {
            my ($args) = @_;
    
            return ($_LOGGER ? $_LOGGER : uLog::_new ( $args ));
    }
    
    sub _init {
            my ($self, $args) = @_;
    
            my ($sApp) = ($0 =~ /.*\/(.*)/);
            foreach my $sKey ( keys %{ $args }) {
                    my $sValue = $args->{ $sKey };
                    if ($sValue) {
                            if      ($sKey eq "level") {
                                    $self->{_iLogLevel} = $hrefLevels->{ $sValue } if ( $hrefLevels->{ $sValue } );
                            } elsif ($sKey eq "service") {
                                    $self->{_sService} = $sValue;
                            } elsif ($sKey eq "ticket") {
                                    $self->{_sTicket} = $sValue;
                            } elsif ($sKey eq "module") {
                                    $self->{_sModule} = $sValue;
                            }
                    }
            }
            my $sFileName = ($self->{_sService} eq $NODATAFIELD ? $sApp : $self->{_sService});
            $sFileName .= ($self->{_sModule} eq $NODATAFIELD ? "" : "_" . $self->{_sModule}) . ".log";
            foreach my $sDir (@{ $DIRORDER }) {
                    if (-w $sDir) {
    
                            $self->{_sLogFile} = $sDir . $sFileName;
                            last;
                    }
            }
    }
    
    sub _open {
            my $self = shift;
    
            $self->{ _LOG_FH } = new IO::File ">> " . $self->{_sLogFile} if ( $self->{_sLogFile} );
            $self->{ _LOG_FH }->autoflush( 1 );
    }
    
    sub _getLine {
            my $iCallerLevel = 2;
            my ($package, $filename, $line,
                    $subroutine, $hasargs,
                    $wantarray, $evaltext, $is_require, 
                    $hints, $bitmask) = caller($iCallerLevel);
            $filename =~ s/^.*\///g;
            return $filename  . ":" . $line;
    }
    
    sub _round {
            my $iVal = shift;
            my $iInt = int $iVal;
    
            return $iVal - $iInt >= 0.5 ? $iInt + 1 : $iInt;
    }
    
    sub _log {
            my ($self, $sType, $sMsg, $iCode) = @_;
    
            return if ($hrefLevels->{ $sType } > $self->{_iLogLevel});
            my $iEpochSeconds      = time();
            my $iEpochMilliseconds = 0;
            if ($HAS_TIME_HIRES) {
                    ($iEpochSeconds, $iEpochMilliseconds) =  Time::HiRes::gettimeofday();
                    $iEpochMilliseconds = _round($iEpochMilliseconds / 1000 );
            }
            unless ($self->{_iDelta}) {
                    $self->{_iDelta} = $iEpochSeconds + ($iEpochMilliseconds /1000);
            }
            $self->_open unless($self->{ _LOG_FH } && -w $self->{_sLogFile});
            return unless $self->{ _LOG_FH };
            my $tmp = $self->{ _LOG_FH };
            $sMsg =~ s/\n/\\n/gsi;
            (my $sTmpformat = $DATEFORMAT) =~ s/\%Q/$iEpochMilliseconds/g;
            my $sDelta = sprintf("%.3f", ($iEpochSeconds + ($iEpochMilliseconds /1000)) - $self->{_iDelta});
            $sTmpformat =~ s/\%q/$sDelta/g;
    
            (my $seg, my $min, my $hora, my $dia, my $mes, my $anho, my @zape) = localtime(time);
            $mes++;
            $anho+=1900;
            my $fecha = sprintf("%04d/%02d/%02d %02d:%02d:%02d", $anho, $mes, $dia, $hora, $min, $seg);
    
            print $tmp sprintf("[%s] %s %s:%s:%s:%s:%s %s\n",
                    $fecha,
                    $sType,
                    $self->{_sService},
                    $self->{_sModule},
                    $self->{_sMachine},
                    $self->{_sUser},
                    _getLine(),
                    #$self->{_sTicket},
                    #$self->{_iCounter},
                    #$iCode || 0,
                    $sMsg);
            $self->{_iCounter}++;
    }
    
    sub DESTROY {
            my $self = shift;
            undef $self->{ _LOG_FH } if ($self->{ _LOG_FH });
    }
    
    sub ResetDelta {
            my ( $self ) = @_;
            $self->{_iDelta} = 0;
    }
    
    sub LOG {
            my ( $self, $sType, $sMsg, $iCode ) = @_;
            $self->_log($sType, $sMsg, $iCode) if (defined $hrefLevels->{ $sType });
    }
    
    sub FAT {
            my ( $self, $sMsg, $iCode ) = @_;
            $self->_log("FAT", $sMsg, $iCode);
    }
    
    sub ERR {
            my ( $self, $sMsg, $iCode ) = @_;
            $self->_log("ERR", $sMsg, $iCode);
    }
    
    sub WAR {
            my ( $self, $sMsg, $iCode ) = @_;
            $self->_log("WAR", $sMsg, $iCode);
    }
    
    sub INF {
            my ( $self, $sMsg, $iCode ) = @_;
            $self->_log("INF", $sMsg, $iCode);
    }
    
    sub DEB {
            my ( $self, $sMsg, $iCode ) = @_;
            $self->_log("DEB", $sMsg, $iCode);
    }
    
    sub VER {
            my ( $self, $sMsg, $iCode ) = @_;
            $self->_log("VER", $sMsg, $iCode);
    }
    
    1;
    

    copy | embed

    0 comments - tagged in  posted by yvoictra on Jan 16, 2010 at 4:14 a.m. EST
  • sort filezilla server log entries by session id
    #!/bin/bash
    
    #
    # entry example
    #
    # (1579051) 10/16/2009 0:02:13 AM - (not logged in) (192.168.1.11)> USER chris
    #
    # sort -k1n fzs-2009-10-16.log
    # does not work properly because when the session id and timestamp are the same
    # it goes on and tries to sort based on the message
    # if the timestamp granularity was high enough it would work (and so much faster!)
    #
    
    [ $# -ne 1 ] && echo "number of args required is 1" && exit 1
    
    [ ! -e $1 ] && echo "file $1 does not exist" && exit 2
    
    FILEPATH=`dirname $1`
    LOGNAME=`basename $1`
    
    LOGNAME_SORTED=${FILEPATH}/${LOGNAME}".sorted"
    SID_SORTED_FILENAME=${FILEPATH}/"fzlog_sid_sorted.$$"
    
    rm -f $LOGNAME_SORTED
    
    awk '{ split( $1, L, "\\(|\\)" ); print L[ 2 ]; }' $1 | sort | uniq > ${SID_SORTED_FILENAME}
    
    cat ${SID_SORTED_FILENAME} | while read line
    do
            grep "^($line)" $1 >> ${LOGNAME_SORTED}
    done
    
    rm -f ${SID_SORTED_FILENAME}
    
    exit 0
    

    copy | embed

    0 comments - tagged in  posted by cgv on Jan 05, 2010 at 4:52 a.m. EST
  • arquivo de propriedade do log4j
    # Configura dois appenders (stdout para o console, fileout para um arquivo)
    # para o logger padrão, e configura um nível (INFO). Como todos os
    # loggers que criamos herdam do logger padrãoo, quaisquer loggers que criarmos
    # terão esta configuração
    log4j.rootCategory=INFO, stdout, fileout
    # O primeiro appender escreve para o console
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    # O padrão para apresentação do conteúdo (layout)
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
    # O segundo appender escreve para um arquivo
    log4j.appender.fileout=org.apache.log4j.RollingFileAppender
    log4j.appender.fileout.File=exemplo.log
    # Controla o tamanho máximo do arquivo de log
    log4j.appender.fileout.MaxFileSize=500KB
    # Arquiva arquivos de log (somente um arquivo de backup)
    log4j.appender.fileout.MaxBackupIndex=1
    # O padrãoo para apresentação do conteúdo (layout)
    log4j.appender.fileout.layout=org.apache.log4j.PatternLayout
    log4j.appender.fileout.layout.ConversionPattern=(%F:%L) %p %t %c - %m%n
    

    copy | embed

    0 comments - tagged in  posted by mwanalezi on Nov 16, 2009 at 9:00 p.m. EST
  • Shows svn check ins for a specific user in a certain date range.
    $ svn log -r {2009-07-09}:{2007-08-17}  | grep -a3 <username>
    

    copy | embed

    0 comments - tagged in  posted by isagoksu on Jul 31, 2009 at 1:41 p.m. EDT
  • extracting unique IPs from a log
    egrep -o "10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" access.log | sort -u
    

    copy | embed

    0 comments - tagged in  posted by w00kie on Jul 13, 2009 at 5:55 a.m. EDT
  • simple class to work with SOS (http://solutions.powerflasher.com/products/sosmax/) v2
    import mx.utils.Delegate;
    
    class com.cyberhull.SOS {
    
    	public static var MOVIE_FILTER:Object = {
        		_alpha : true,
        		blendMode: false,
        		cacheAsBitmap: false,
        		_currentframe: true,
        		_droptarget: false,
        		enabled: false,
        		filters: false,
        		focusEnabled: false,
        		_focusrect: false,
        		forceSmoothing: false,
        		_framesloaded: false,
        		_height: true,
        		_highquality: false,
        		hitArea: false,
        		_lockroot: false,
        		menu: false,
        		_name : true,
        		opaqueBackground: false,
       			_parent: false,
       			_quality: false,
     			_rotation: true,
     			scale9Grid: false,
     			scrollRect: false,
     			_soundbuftime: false,
     			tabChildren: false,
     			tabEnabled: false, 
     			tabIndex: false,
        		_target : true,
        		_totalframes: false,
        		trackAsMenu: false,
        		transform: false,
        		_url:false,
        		useHandCursor: false,
        		_visible: false,
        		_width: false,
        		_x: true,
        		_xmouse: false,
        		_xscale: true,
        		_y: true,
        		_ymouse: false,
        		_yscale: true	
    		};
    
    	private static var _filters:Object = {};
    
    	private var _sendOnConnect:Array = [];
    	private var _socket:XMLSocket;
    	
    	private var _send:Function;
    	
    	private static var _instance:SOS; 
    		
    	public function SOS(host:String, port:Number) {
    		_socket = new XMLSocket();
    		_socket.onConnect = Delegate.create(this, handleConnect);
    		_socket.connect(host?host:"localhost", port?port:4444);
    		
    		_instance = this;
    	}	
    
    	private function handleConnect(success:Boolean) : Void {
    		if (!success) {
    			trace("Unable to connect to SOS!");
    			_send = trace;
    		} else {
    			trace("Connected to SOS!");
    			_send = Delegate.create(_socket, _socket.send);
    			SOS.info("SOS connected!");
    		}
    			
    		for (var i:Number = 0; i<_sendOnConnect.length; i++) {
    			_send(_sendOnConnect[i]);	
    		}		
    	
    	}
    	
    		
    	private function sendXML(xml:String):Void {
    		if (_send) {
    			_send(xml);
    			return;
    		}
    		
    		_sendOnConnect.push(xml);
    	}
    	
        private static function serialize(obj:Object, all:Array, indent:String):String {
        	
        	if (!indent) indent = "";
        	
        	if (typeof(obj)=="string") return "\""+obj+"\"";
        	if (typeof(obj)=="number") return String(obj);
    		if (typeof(obj)=="boolean") return String(obj);
    		if (obj==null) return "null";
    		if (obj==undefined) return "undefined";
    		
    		if (!all) {
    			all = [];
    		} else {
    			for (var i:Number =0; i< all.length; i++) if (all[i]===obj) {
    				return "ref#"+obj.toString();
    			}
    		}
    		all.push(obj);
    		
    		if (obj instanceof Array) {			
    			var s:String = "[\n";
    			var delim:String = "";
    			for (var i:Number=0; i<obj.length; i++) {
    				s+=delim;
    				s+=indent;
    				s+=serialize(obj[i], all.concat(), indent+"\t");
    				delim = ",\n";
    			}		
    			s+="\n"+indent.substr(1)+"]";
    			return s;
    		}
        	    	
        	var filter:Object = findFilter(obj);
        	
         	var s:String = "{\n"; 
         	var delim:String = ""; 	
        	for (var p in filter?filter:obj){
        		if (typeof(obj[p])=="function") continue;
    			if (filter && !filter[p]) continue;
        		s += delim;
        		s += indent + p + ": "+serialize(obj[p], all.concat(), indent+"\t");	
        		delim = ",\n";
        	}
        	s+="\n"+indent.substr(1)+"}";
        	return s;
        }
        
        private static function findFilter(obj:Object): Object {
        	for (var c:String in _filters) {
        		var func:Function = eval(c);
        		if (obj instanceof func) return _filters[c];
        	}
        	
        	return null;
        }
        
        public static function registerFilter(constr:String, filter:Object): Void {
        	var f:Function = function (): Void {
        	};
        	
        	f.prototype = MOVIE_FILTER;
    		var o:Object = new f();
        	for (var p:String in filter) {
        		o[p] = filter[p];
        	}
        		
        	_filters[constr] = o; 	
        }
        
        public static function connect(host:String, port:Number):Void {
        	if (_instance) return;
        	new SOS(host, port);
        }
        
        public static function send(message:Object, key:String, comment:Object): Void {
        	var xml:String;
        	
        	if (typeof(message)!="string") message = serialize(message);
        	
        	if (!comment) {
        		xml = "!SOS<showMessage key='"+key+"'>"+message+"</showMessage>";
        	} else {
        		if (typeof(comment)!="string") comment = serialize(comment); 
        		xml = "!SOS<showFoldMessage key='"+key+"'>"
          			+ "<title>"+message+"</title>"
          			+ "<message>"+comment+"</message>"
          			+ "</showFoldMessage>" 
        	}
        	
        	
        	connect();
        	_instance.sendXML(xml);
    
        }
        
        
        public static function fatal(message:Object, comment:Object):Void {
        	send(message, "fatal", comment);
        }
        
        public static function error(message:Object, comment:Object):Void {
        	send(message, "error", comment);
        }
        
        public static function warn(message:Object, comment:Object):Void {
        	send(message, "warn", comment);
        }
        
        public static function info(message:Object, comment:Object):Void {
        	send(message, "info", comment);
        }
        
        public static function debug(message:Object, comment:Object): Void {
        	send(message, "debug", comment);
        }
        
        
        	
    }
    

    copy | embed

    0 comments - tagged in  posted by ambienthack on Jun 05, 2009 at 3:18 a.m. EDT
  • simple class to work with SOS (http://solutions.powerflasher.com/products/sosmax/)
    import mx.utils.Delegate;
    
    class com.cyberhull.SOS {
    
    	private var _sendOnConnect:Array = [];
    	private var _socket:XMLSocket;
    	
    	private var _send:Function;
    	
    	private static var _instance:SOS; 
    		
    	public function SOS(port:Number) {
    		_socket = new XMLSocket();
    		_socket.onConnect = Delegate.create(this, handleConnect);
    		_socket.connect("localhost", port?port:4444);
    	}	
    	
    	private function handleConnect(success:Boolean) : Void {
    		if (!success) {
    			trace("Unable to connect to SOS!");
    			_send = trace;
    		} else {
    			trace("Connected to SOS!");
    			_send = Delegate.create(_socket, _socket.send);
    			SOS.info("SOS connected!");
    		}
    			
    		for (var i:Number = 0; i<_sendOnConnect.length; i++) {
    			_send(_sendOnConnect[i]);	
    		}		
    	
    	}
    	
    		
    	private function sendXML(xml:String):Void {
    		if (_send) {
    			_send(xml);
    			return;
    		}
    		
    		_sendOnConnect.push(xml);
    	}
    	
        private static function serialize(obj:Object, all:Array):String {
        	
        	if (typeof(obj)=="string") return "\""+obj+"\"";
        	if (typeof(obj)=="number") return String(obj);
    		if (typeof(obj)=="boolean") return String(obj);
    		if (obj==null) return "null";
    		if (obj==undefined) return "undefined";
    		
    		if (!all) {
    			all = [];
    		} else {
    			for (var i:Number =0; i< all.length; i++) if (all[i]===obj) {
    				return "#"+obj.toString();
    			}
    		}
    		all.push(obj);
    		
    		if (obj instanceof Array) {			
    			var s:String = "[";
    			var delim:String = "";
    			for (var i:Number=0; i<obj.length; i++) {
    				s+=delim;
    				s+=serialize(obj[i], all);
    				delim = ", ";
    			}		
    			s+="]";
    			return s;
    		}
        	
        	var s:String = "{";  	
        	for (var p in obj){
        		if (typeof(obj[p])=="function") continue;
        		s += p + ": "+serialize(obj[p], all)+", ";	
        	}
        	
        	s+="}";
        	return s;
        }
        
        private static function send(message:String, key:String): Void {
        	var xml:String = "!SOS<showMessage key='"+key+"'>"+message+"</showMessage>";
        	
        	if (!_instance) _instance = new SOS();
        	_instance.sendXML(xml);
    
        }
        
        private static function sendFolded(title:String, message:String, key:String):Void {
        
        }
        
        public static function fatal(message:Object):Void {
        	send(serialize(message), "fatal");
        }
        
        public static function error(message:Object):Void {
        	send(serialize(message), "error");
        }
        
        public static function warn(message:Object):Void {
        	send(serialize(message), "warn");
        }
        
        public static function info(message:Object):Void {
        	send(serialize(message), "info");
        }
        
        public static function debug(message:Object): Void {
        	send(serialize(message), "debug");
        }
        
        
        	
    }
    

    copy | embed

    2 comments - tagged in  posted by ambienthack on Apr 08, 2009 at 10:52 a.m. EDT
  • database change log behavior for cakephp
    <?php
    /**
     * Logs saves and deletes of any model
     * 
     * Requires the following to work as intended :
     * 
     * - "Log" model ( empty but for a order variable [created DESC]
     * - "logs" table with these fields required :
     *     - id			[int]			: 
     *     - title 		[string] 		: automagically filled with the display field of the model that was modified.
     * 	   - created	[date/datetime] : filled by cake in normal way
     * 
     * - actsAs = array("Logable"); on models that should be logged
     * 
     * Optional extra table fields for the "logs" table :
     * 
     * - "description" 	[string] : Fill with a descriptive text of what, who and to which model/row :  
     * 								"Contact "John Smith"(34) added by User "Administrator"(1).
     * 
     * or if u want more detail, add any combination of the following :
     * 
     * - "model"    	[string] : automagically filled with the class name of the model that generated the activity.
     * - "model_id" 	[int]	 : automagically filled with the primary key of the model that was modified.
     * - "action"   	[string] : automagically filled with what action is made (add/edit/delete) 
     * - "user_id"  	[int]    : populated with the supplied user info. (May be renamed. See bellow.)
     * - "change"   	[string] : depending on setting either : 
     * 							[name (alek) => (Alek), age (28) => (29)] or [name, age]
     * 
     * - "version_id"	[int]	 : cooperates with RevisionBehavior to link the the shadow table (thus linking to old data)
     * 
     * Remember that Logable behavior needs to be added after RevisionBehavior. In fact, just put it last to be safe.
     * 
     * Optionally register what user was responisble for the activity :
     * 
     * - Supply configuration only if defaults are wrong. Example given with defaults :
     * 
     * class Apple extends AppModel {
     * 		var $name = 'Apple';
     * 		var $actsAs = array('Logable' => array('userModel' => 'User', 'userKey' => 'user_id'));
     *  [..]
     * 
     * - In AppController (or single controller if only needed once) add these lines to beforeFilter : 
     * 
     *   	if (sizeof($this->uses) && $this->{$this->modelClass}->Behaviors->attached('Logable')) {
     *			$this->{$this->modelClass}->setUserData($this->activeUser);
     *		}
     *
     *   Where "$activeUser" should be an array in the standard format for the User model used :
     * 
     *   $activeUser = array( $UserModel->alias => array( $UserModel->primaryKey => 123, $UserModel->displayField => 'Alexander'));
     *   // any other key is just ignored by this behaviour.
     * 
     * @author Alexander Morland (alexander#maritimecolours.no)
     * @co-author Eskil Mjelva Saatvedt
     * @co-author Ronny Vindenes
     * @co-author Carl Erik Fyllingen
     * @category Behavior
     * @version 2.1
     * @modified 12.feb 2009 by ronny
     */
    
    class LogableBehavior extends ModelBehavior 
    {
    	public $user = NULL;
    	public $UserModel = FALSE;
        public $settings = array();
    	public $defaults = array(
    			'userModel' => 'User',
    			'userKey' => 'user_id',
    			'change' => 'list',
    			'description_ids' => TRUE,
    			'skip' => array(),
    			'ignore' => array()
    		);
    	/**
    	 * Cake called intializer
    	 * Config options are :
    	 *    userModel 		: 'User'. Class name of the user model you want to use (User by default), if you want to save User in log
    	 *    userKey   		: 'user_id'. The field for saving the user to (user_id by default).
    	 * 	  change    		: 'list' > [name, age]. Set to 'full' for [name (alek) => (Alek), age (28) => (29)]
    	 * 	  description_ids 	: TRUE. Set to FALSE to not include model id and user id in the title field
    	 *    skip  			: array(). String array of actions to not log
    	 *
    	 * @param Object $Model
    	 * @param array $config
    	 */
    	function setup(&$Model, $config = array()) {
    		if (!is_array($config)) {
    			$config = array();
    		}	
    		$this->settings[$Model->alias] = array_merge_recursive($this->defaults, $config);
    		$this->settings[$Model->alias]['ignore'] = (array) $this->settings[$Model->alias]['ignore'];
    		$this->settings[$Model->alias]['ignore'][] = $Model->primaryKey; 
    				
    		App::import('model','Log');
    		$this->Log = new Log();
    		if ($this->settings[$Model->alias]['userModel'] != $Model->alias) {
    			if (App::import('model',$this->settings[$Model->alias]['userModel'])) {
    	        	$this->UserModel = new $this->settings[$Model->alias]['userModel']();
    	        }
    		} else {
    			$this->UserModel = $Model;
    		}       
    	}
    	
    	function settings(&$Model) {
    		return $this->settings[$Model->alias];
    	}
    	
    	/**
    	 * Useful for getting logs for a model, takes params to narrow find. 
    	 * This method can actually also be used to find logs for all models or
    	 * even another model. Using no params will return all activities for
    	 * the models it is called from.
    	 *
    	 * Possible params :
    	 * 'model' 		: mixed  (NULL) String with className, NULL to get current or FALSE to get everything
    	 * 'action' 	: string (NULL) String with action (add/edit/delete), NULL gets all
    	 * 'order' 		: string ('created DESC') String with custom order
    	 * 'conditions  : array  (array()) Add custom conditions
    	 * 'model_id'	: int	 (NULL) Add a int 
    	 * 
    	 * (remember to use your own user key if you're not using 'user_id')
    	 * 'user_id' 	: int 	 (NULL) Defaults to all users, supply id if you want for only one User
    	 * 
    	 * @param Object $Model
    	 * @param array $params
    	 * @return array
    	 */
    	function findLog(&$Model, $params = array()) {
    		$defaults = array(
    			 'model' => NULL,
    			 'action' => NULL,
    			 'order' => 'created DESC',
    			 $this->settings[$Model->alias]['userKey'] => NULL,
    			 'conditions' => array(),
    			 'model_id' => NULL,
    			 'fields' => array(),
    			 'limit' => 50,
    		);
    		$params = array_merge($defaults, $params);
    		$options = array('order' => $params['order'], 'conditions' => $params['conditions'], 'fields' => $params['fields'], 'limit' => $params['limit']);
    		if ($params['model'] === NULL) {
    			$params['model'] = $Model->alias;
    		}
    		if ($params['model']) {
    	    	if (isset($this->Log->_schema['model'])) {
    	    		$options['conditions']['model'] = $params['model'];
    	    	} elseif (isset($this->Log->_schema['description'])) {    		
    	    		$options['conditions']['description LIKE '] = $params['model'].'%';
    	    	} else {
    	    		return FALSE;
    	    	}
    		}
        	if ($params['action'] && isset($this->Log->_schema['action'])) {
        		$options['conditions']['action'] = $params['action'];
        	}     	
    		if ($params[ $this->settings[$Model->alias]['userKey'] ] && $this->UserModel && is_numeric($params[ $this->settings[$Model->alias]['userKey'] ])) {
    			$options['conditions'][$this->settings[$Model->alias]['userKey']] = $params[ $this->settings[$Model->alias]['userKey'] ];
    		}
    		if ($params['model_id'] && is_numeric($params['model_id'])) {
    			$options['conditions']['model_id'] = $params['model_id'];
    		}
        	return $this->Log->find('all',$options);
    	}
    	
    	/**
    	 * Get list of actions for one user.
    	 * Params for getting (one line) activity descriptions 
    	 * and/or for just one model 
    	 *
    	 * @example $this->Model->findUserActions(301,array('model' => 'BookTest'));
    	 * @example $this->Model->findUserActions(301,array('events' => true));
    	 * @example $this->Model->findUserActions(301,array('fields' => array('id','model'),'model' => 'BookTest');
    	 * @param Object $Model
    	 * @param int $user_id
    	 * @param array $params
    	 * @return array
    	 */
    	function findUserActions(&$Model, $user_id, $params = array()) {
    		if (!$this->UserModel) {
    			return NULL;
    		}
    		// if logged in user is asking for her own log, use the data we allready have
    		if ( isset($this->user) 
    			 && isset($this->user[$this->UserModel->alias][$this->UserModel->primaryKey]) 
    			 && $user_id == $this->user[$this->UserModel->alias][$this->UserModel->primaryKey] 
    			 && isset($this->user[$this->UserModel->alias][$this->UserModel->displayField]) ) {
    			$username = $this->user[$this->UserModel->alias][$this->UserModel->displayField];
    		} else {
    			$this->UserModel->recursive = -1;
    			$user = $this->UserModel->find(array($this->UserModel->primaryKey => $user_id));
    			$username = $user[$this->UserModel->alias][$this->UserModel->displayField];
    		}
    		$fields = array();
    		if (isset($params['fields'])) {
    			if (is_array($params['fields'])) {
    				$fields = $params['fields'];
    			} else {
    				$fields = array($params['fields']);
    			}
    		}
    		$conditions = array($this->settings[$Model->alias]['userKey'] => $user_id);
    		if (isset($params['model'])) {
    			$conditions['model'] = $params['model'];
    		}
    		$data = $this->Log->find('all', array(
    			'conditions' => $conditions,
    			'recursive' => -1,
    			'fields' => $fields
    		));
    		if (! isset($params['events']) || (isset($params['events']) && $params['events'] == false)) {
    			return $data;
    		}
    		$result = array();
    		foreach ($data as $key => $row) {$one = $row['Log'];
    			$result[$key]['Log']['id'] = $one['id'];
    			$result[$key]['Log']['event'] = $username;
    			// have all the detail models and change as list : 
    			if (isset($one['model']) && isset($one['action']) && isset($one['change']) && isset($one['model_id'])) {
    				 if ($one['action'] == 'edit') {
    				 	$result[$key]['Log']['event'] .= ' edited '.$one['change'].' of '.low($one['model']).'(id '.$one['model_id'].')';
    				 	//	' at '.$one['created']; 
    				 } elseif ($one['action'] == 'add') {
    				 	$result[$key]['Log']['event'] .= ' added a '.low($one['model']).'(id '.$one['model_id'].')';
    				 } elseif ($one['action'] == 'delete') {
    				 	$result[$key]['Log']['event'] .= ' deleted the '.low($one['model']).'(id '.$one['model_id'].')';
    				 }
    					 	
    			} elseif ( isset($one['model']) && isset($one['action'])  && isset($one['model_id']) ) { // have model,model_id and action
                     if ($one['action'] == 'edit') {
    				 	$result[$key]['Log']['event'] .= ' edited '.low($one['model']).'(id '.$one['model_id'].')';
    				 	//	' at '.$one['created']; 
    				 } elseif ($one['action'] == 'add') {
    				 	$result[$key]['Log']['event'] .= ' added a '.low($one['model']).'(id '.$one['model_id'].')';
    				 } elseif ($one['action'] == 'delete') {
    				 	$result[$key]['Log']['event'] .= ' deleted the '.low($one['model']).'(id '.$one['model_id'].')';
    				 }
    			} else { // only description field exist
                    $result[$key]['Log']['event'] = $one['description'];
    			}
    				
    		}
    		return $result;
    	}
        /**
         * Use this to supply a model with the data of the logged in User.
         * Intended to be called in AppController::beforeFilter like this :
         *   
     	 *   	if ($this->{$this->modelClass}->Behaviors->attached('Logable')) {
     	 *			$this->{$this->modelClass}->setUserData($activeUser);/
     	 *		}
         *
         * The $userData array is expected to look like the result of a 
         * User::find(array('id'=>123));
         * 
         * @param Object $Model
         * @param array $userData
         */
    	function setUserData(&$Model, $userData = null) {
    		if ($userData) {
    			$this->user = $userData;
    		}
    	}
    		
    	/**
    	 * Used for logging custom actions that arent crud, like login or download.
    	 *
    	 * @example $this->Boat->customLog('ship', 66, array('title' => 'Titanic heads out'));
    	 * @param Object $Model
    	 * @param string $action name of action that is taking place (dont use the crud ones)
    	 * @param int $id  id of the logged item (ie model_id in logs table)
    	 * @param array $values optional other values for your logs table
    	 */
    	function customLog(&$Model, $action, $id, $values = array()) {		
    		$logData['Log'] = $values;
    		/** @todo clean up $logData */
    		if (isset($this->Log->_schema['model_id']) && is_numeric($id)) {
    			$logData['Log']['model_id'] = $id;
    		}
    		$title = NULL;
    		if (isset($values['title'])) {
        		$title = $values['title']; 
        		unset($logData['Log']['title']);
    		}
        	$logData['Log']['action'] = $action;
        	$this->_saveLog($Model, $logData, $title);
    	}
    	
    	function clearUserData(&$Model) {
    		$this->user = NULL;
    	}
    	
    	function setUserIp(&$Model, $userIP = null) {
    		$this->userIP = $userIP;
    	}
    	
    
    	
    	function beforeDelete(&$Model) {
    		if (isset($this->settings[$Model->alias]['skip']['delete']) && $this->settings[$Model->alias]['skip']['delete']) {
    			return true;
    		}
    		$Model->recursive = -1;
    		$Model->read();
    		return true;
    	}
    	
    	function afterDelete(&$Model) {
    		if (isset($this->settings[$Model->alias]['skip']['delete']) && $this->settings[$Model->alias]['skip']['delete']) {
    			return true;
    		}
    		$logData = array();
    		 if (isset($this->Log->_schema['description'])) {
    		 	$logData['Log']['description'] = $Model->alias;
    		 	if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
    		 		$logData['Log']['description'] .= ' "'.$Model->data[$Model->alias][$Model->displayField].'"';
    		 	}
    			if ($this->settings[$Model->alias]['description_ids']) {
    				$logData['Log']['description'] .= ' ('.$Model->id.') ';
    			}
    			$logData['Log']['description'] .= __('deleted',TRUE);
    		 }		
        	$logData['Log']['action'] = 'delete'; 	
        	$this->_saveLog($Model, $logData);
    	}
        
    	function beforeSave(&$Model) {
            if (isset($this->Log->_schema['change']) && $Model->id) {
            	$this->old = $Model->find('first',array('conditions'=>array($Model->primaryKey => $Model->id),'recursive'=>-1));
            }
            return true;
    	}
    	
        function afterSave(&$Model,$created) {
    		if (isset($this->settings[$Model->alias]['skip']['add']) && $this->settings[$Model->alias]['skip']['add'] && $created) {
    			return true;
    		} elseif (isset($this->settings[$Model->alias]['skip']['edit']) && $this->settings[$Model->alias]['skip']['edit'] && !$created) {
    			return true;
    		}
    		$keys = array_keys($Model->data[$Model->alias]);
    		$diff = array_diff($keys,$this->settings[$Model->alias]['ignore']);
    		if (sizeof($diff) == 0 && empty($Model->logableAction)) {
    			return false;
    		}
         	if ($Model->id) {
        		$id = $Model->id;
        	} elseif ($Model->insertId) {
        		$id = $Model->insertId;
        	}     	
            if (isset($this->Log->_schema['model_id'])) {
       			$logData['Log']['model_id'] = $id;
        	}
    		if (isset($this->Log->_schema['description'])) {		
    	    	$logData['Log']['description'] = $Model->alias.' ';
    		 	if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
    		 		$logData['Log']['description'] .= '"'.$Model->data[$Model->alias][$Model->displayField].'" ';
    		 	}
    	    	
    	        if ($this->settings[$Model->alias]['description_ids']) {
    	        	$logData['Log']['description'] .= '('.$id.') ';
    	        }
    										
    	    	if ($created) {
    	    		$logData['Log']['description'] .= __('added',TRUE);
    	    	} else {
    	    		$logData['Log']['description'] .= __('updated',TRUE);   
    	    	}  
    		}     
    		if (isset($this->Log->_schema['action'])) {					
    	    	if ($created) {
    	    		$logData['Log']['action'] = 'add';
    	    	} else { 
    	    		$logData['Log']['action'] = 'edit'; 		
    	    	}  
    			
    		}
        	if (isset($this->Log->_schema['change'])) {
        		$logData['Log']['change'] = '';
        		$db_fields = array_keys($Model->_schema);
        		$changed_fields = array();
        		foreach ($Model->data[$Model->alias] as $key => $value) {
        			if (isset($Model->data[$Model->alias][$Model->primaryKey]) && !empty($this->old) && isset($this->old[$Model->alias][$key])) {
        				$old = $this->old[$Model->alias][$key];
        			} else {
        				$old = '';
        			}
        			if ($key != 'modified' 
    	    			&& !in_array($key, $this->settings[$Model->alias]['ignore'])
    	    			&& $value != $old && in_array($key,$db_fields) ) 
    	    			{
    	    				if ($this->settings[$Model->alias]['change'] == 'full') {
    	    					$changed_fields[] = $key . ' ('.$old.') => ('.$value.')';
    	    				} else {
    	    					$changed_fields[] = $key;	
    	    				}    				
    	    			}
        		}
        		$changes = sizeof($changed_fields);
        		if ($changed_fields == 0) {
        			return true;
        		} 
        		$logData['Log']['change'] = implode(', ',$changed_fields);
        		$logData['Log']['changes'] = $changes;		
        	}  
        	$this->_saveLog($Model, $logData);
        }
        
        /**
         * Does the actual saving of the Log model. Also adds the special field if possible.
         * 
         * If model field in table, add the Model->alias
         * If action field is NOT in table, remove it from dataset
         * If the userKey field in table, add it to dataset
         * If userData is supplied to model, add it to the title 
         *
         * @param Object $Model
         * @param array $logData
         */
        function _saveLog(&$Model, $logData, $title = null) {  
        	if ($title !== NULL) {
        		$logData['Log']['title'] = $title;
        	} elseif ($Model->displayField == $Model->primaryKey) {
        		$logData['Log']['title'] = $Model->alias . ' ('. $Model->id.')';
        	} elseif (isset($Model->data[$Model->alias][$Model->displayField])) {
        		$logData['Log']['title'] = $Model->data[$Model->alias][$Model->displayField];
        	} else {
        		$Model->recursive = -1;
        		$Model->read(array($Model->displayField));
        		$logData['Log']['title'] = $Model->data[$Model->alias][$Model->displayField];
        	}
        		
        	if (isset($this->Log->_schema['model'])) {
        		$logData['Log']['model'] = $Model->alias;
        	}
        	
        	if (isset($this->Log->_schema['model_id']) && !isset($logData['Log']['model_id'])) {
        		if ($Model->id) {
        			$logData['Log']['model_id'] = $Model->id;
        		} elseif ($Model->insertId) {
        			$logData['Log']['model_id'] = $Model->insertId;
        		}     		
        	}
    		
        	if (!isset($this->Log->_schema[ 'action' ])) {
        		unset($logData['Log']['action']);
        	} elseif (isset($Model->logableAction) && !empty($Model->logableAction)) {
        		$logData['Log']['action'] = implode(',',$Model->logableAction); // . ' ' . $logData['Log']['action'];
        		unset($Model->logableAction);
        	}
        	
        	if (isset($this->Log->_schema[ 'version_id' ]) && isset($Model->version_id)) {
        		$logData['Log']['version_id'] = $Model->version_id;
        		unset($Model->version_id);
        	}
        	
        	if (isset($this->Log->_schema[ 'ip' ]) && $this->userIP) {
        		$logData['Log']['ip'] = $this->userIP;
        	}
        	
        	if (isset($this->Log->_schema[ $this->settings[$Model->alias]['userKey'] ]) && $this->user) {
        		$logData['Log'][$this->settings[$Model->alias]['userKey']] = $this->user[$this->UserModel->alias][$this->UserModel->primaryKey];
        	}  	
        	
            if (isset($this->Log->_schema['description'])) {
            	if ($this->user && $this->UserModel) {
            		$logData['Log']['description'] .= ' by '.$this->settings[$Model->alias]['userModel'].' "'.
            				$this->user[$this->UserModel->alias][$this->UserModel->displayField].'"';
            		if ($this->settings[$Model->alias]['description_ids']) {
            			$logData['Log']['description'] .= ' ('.$this->user[$this->UserModel->alias][$this->UserModel->primaryKey].')';
            		}
        										
            	} else { 
            		// UserModel is active, but the data hasnt been set. Assume system action.
            		$logData['Log']['description'] .= ' by System';
            	}
        		$logData['Log']['description'] .= '.';    		
        	} 	
        	$this->Log->create($logData);
        	$this->Log->save(NULL,FALSE);    	
        }
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by alkemann on Mar 25, 2009 at 4:49 p.m. EDT
  • Create a logger in Ruby
    require 'logger'
    
    $logger = Logger.new(STDOUT)
    $logger.level = Logger::DEBUG
    $logger.datetime_format = "%H:%M:%S"
    

    copy | embed

    0 comments - tagged in  posted by oskarnrk on Mar 06, 2009 at 3:33 a.m. EST
  • Retrieving a logger in Symfony
    <?php
    $logger = sfContext::getInstance()->getLogger();
    ?>
    

    copy | embed

    0 comments - tagged in  posted by brenes on Feb 25, 2009 at 4:42 a.m. EST
  • Shrink database
    -- shrink log
    -- http://support.microsoft.com/kb/907511
    BACKUP LOG AdInsure_TriglavOsiguranje TO DISK = 'D:\log.bak'
    
    DBCC SHRINKFILE ('TILIA_ZAVAR_DATA', 1000) WITH NO_INFOMSGS
    DBCC SHRINKFILE ('TILIA_ZAVAR_LOG', 1000) WITH NO_INFOMSGS
    
    -- Create the temporary table...
    CREATE TABLE #tblResults
    (
       [name]   nvarchar(20),
       [rows]   int,
       [reserved]   varchar(18),
       [reserved_int]   int default(0),
       [data]   varchar(18),
       [data_int]   int default(0),
       [index_size]   varchar(18),
       [index_size_int]   int default(0),
       [unused]   varchar(18),
       [unused_int]   int default(0)
    )
    
    
    -- Populate the temp table...
    EXEC sp_MSforeachtable @command1=
             "INSERT INTO #tblResults
               ([name],[rows],[reserved],[data],[index_size],[unused])
              EXEC sp_spaceused '?'"
       
    -- Strip out the " KB" portion from the fields
    UPDATE #tblResults SET
       [reserved_int] = CAST(SUBSTRING([reserved], 1, 
                                 CHARINDEX(' ', [reserved])) AS int),
       [data_int] = CAST(SUBSTRING([data], 1, 
                                 CHARINDEX(' ', [data])) AS int),
       [index_size_int] = CAST(SUBSTRING([index_size], 1, 
                                 CHARINDEX(' ', [index_size])) AS int),
       [unused_int] = CAST(SUBSTRING([unused], 1, 
                                 CHARINDEX(' ', [unused])) AS int)
       
    -- Return the results...
    SELECT * FROM #tblResults order by unused_int desc
    

    copy | embed

    0 comments - tagged in  posted by DavidV on Feb 20, 2009 at 2:49 a.m. EST
  • simple php file based logging in one line
    file_put_contents('log_file_name', $data, FILE_APPEND);
    

    copy | embed

    0 comments - tagged in  posted by earonne on Jan 24, 2009 at 6:38 p.m. EST
  • SVN commit with file as log message
    $ svn commit -F msg foo.c
    

    copy | embed

    0 comments - tagged in  posted by JGM564 on Jan 21, 2009 at 8:57 a.m. EST
  • tail for the Flash Player log file
    tail -f ~/Library/Preferences/Macromedia/Flash\ Player/Logs/flashlog.txt
    

    copy | embed

    0 comments - tagged in  posted by gabriel_laet on Jan 14, 2009 at 4:22 p.m. EST
  • Email the backup log
    $smtp = New-Object Net.Mail.SmtpClient -arg $EmailSMTPServer
    $smtp.Send($EmailReportFromAddress,$EmailReportTo,"Exchange Backup Results for " + $ServerName + ": " + $(Get-Date).ToString('MM/dd/yyyy'),$BackupLogFormatted)
    

    copy | embed

    0 comments - tagged in  posted by betahost on Dec 28, 2008 at 12:04 a.m. EST
  • Add line breaks to format the backup log
    $BackupLogFormatted = ""
    Get-Content $BackupLog | foreach { $BackupLogFormatted += $_ + "`n" }
    

    copy | embed

    0 comments - tagged in  posted by betahost on Dec 28, 2008 at 12:03 a.m. EST
Sign up to create your own snipts, or login.