IMPORTANT!

Snipt is going open source. We've toyed with this idea for quite a while, and have finally decided it's the right way to move forward.

A few things:
  • The entire Snipt source code will be released on GitHub under the 3-clause BSD License on Friday, September 10th.
  • While we'd like to think we're perfect, we realize we're only human. By open sourcing the software that runs this website, certain bugs or security flaws may be discovered that could compromise the privacy of your snipts.
  • Only the Lion Burger team will be able to push commits to the Snipt.net site. Contributors should send a pull request to add new features or submit patches.
  • By using this site, you agree not to be too angry or take any legal action against Lion Burger should this whole thing go up in flames some day.
  • Follow us on Twitter for updates.
I agree, close this message
Sign up to create your own snipts, or login.

Latest 100 public snipts » logging The latest public logging snipts.

showing 1-8 of 8 snipts for logging
  • Logging in Zend
    <?php
    Zend_Registry::get('_LOGGER')->debug($text);
    Zend_Registry::get('_LOGGER')->debug(print_r($array, true));
    ?>
    

    copy | embed

    0 comments - tagged in  posted by stupid2 on Aug 09, 2010 at 3:33 a.m. EDT
  • Display warnings module warnings with the logging module
    # Note: This code was pulled from version 0.5.0.6 of the logging module,
    # from the Python subversion repository.
    
    import warnings
    import logging
    
    class NullHandler(logging.Handler):
        """Silence 'No handlers could be found...' messages"""
        def emit(self, record):
            pass
    
    _warnings_showwarning = warnings.showwarning
    def _showwarning(message, category, filename, lineno, file=None, line=None):
        """
        Implementation of showwarnings which redirects to logging, which will first
        check to see if the file parameter is None. If a file is specified, it will
        delegate to the original warnings implementation of showwarning. Otherwise,
        it will call warnings.formatwarning and will log the resulting string to a
        warnings logger named "py.warnings" with level logging.WARNING.
        """
        if file is not None:
            if _warnings_showwarning is not None:
                _warnings_showwarning(message, category, filename, lineno, file)
        else:
            s = warnings.formatwarning(message, category, filename, lineno)
            s = s.split("\n")[0]
            logger = logging.getLogger("py.warnings")
            if not logger.handlers:
                logger.addHandler(NullHandler())
            logger.warning("%s", s)
    
    warnings.showwarning = _showwarning
    

    copy | embed

    0 comments - tagged in  posted by kergoth on Apr 09, 2010 at 6:20 p.m. EDT
  • Log errors in diffent folders/files reflecting the application folder structure.
    <?php
    /**
     * Log PHP's error into separate files. Recommended for use in production site.
     * Should be used in set_error_handler() to handle certain PHP errors (i.e. E_STRICT).
     * @link http://www.php.net/manual/en/function.set-error-handler.php Reference
     */
    function errorHandler($errno, $errstr, $errfile=NULL, $errline=NULL, $errcontext=NULL) {
      // Log uncategorized errors
      if (is_null($errfile)) {
        $errfile = 'errors.log';
      }
    
      // Reconstruct the path
      // define('APP_DIR', '/my/application/')
      // define('LOG_DIR', '/log_dir/')
      // E.g. /my/application/controller/index.php -> /log_dir/controller/index.php
      $pos = strpos($errfile, APP_DIR);
      if ($pos !== FALSE) {
        // Strip off the application directory and attach log directory
        $errfile = LOG_DIR.substr($errfile, $pos + strlen(CMS_ROOT));
      }
      else {
        $errfile = LOG_DIR.$errfile; // E.g. /log_dir/errors.log
      }
      $dir = dirname($errfile);
      // Create dir if necessary
      if (! file_exists($dir)) {
        mkdir($dir, 0775, TRUE);
      }
      
      $logFile = fopen($errfile, 'a');
      fwrite($logFile, date('Y-m-d H:i:s ').$errstr);
      if ($errline) fwrite($logFile, " on line $errline");
      fwrite($logFile, "\n");
      fclose($logFile);
      
      if (PRODUCTION_SITE) // Prevent err msg from being printed out (log errors silently)
        return TRUE;
    
      return FALSE;
    }
    ?>
    

    copy | embed

    0 comments - tagged in  posted by hongster on Jan 21, 2010 at 2:46 a.m. EST
  • File object for logging loggers
    To get access to underlying stream (filelike) object in Python's logging system:
    
    logger.handlers[0].stream
    
    You'll have to figure out which handler for a logger object you want. I've only got one in my sample code. This snipt allows one to pass this stream object into interfaces that are expecting a file object.
    

    copy | embed

    0 comments - tagged in  posted by mredar on Dec 16, 2009 at 7:15 p.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
  • Redirect NSLog to text file
    - (BOOL)redirectNSLog
    {
    	// Create log file
    	[@"" writeToFile:@"/NSLog.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
    	id fileHandle = [NSFileHandle fileHandleForWritingAtPath:@"/NSLog.txt"];
    	if (!fileHandle)	return NSLog(@"Opening log failed"), NO;
    	[fileHandle retain];
    
    	// Redirect stderr
    	int err = dup2([fileHandle fileDescriptor], STDERR_FILENO);
    	if (!err)	return	NSLog(@"Couldn't redirect stderr"), NO;
    	
    	return	YES;
    }
    

    copy | embed

    0 comments - tagged in  posted by jeroenbourgois on Nov 11, 2009 at 4:41 a.m. EST
  • 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
  • jQuery Logging Function
    //	Found here: http://happygiraffe.net/blog/archives/2007/09/26/jquery-logging
    
    //	jQuery Logging Function
    jQuery.fn.log = function (msg) {
    	console.log("%s: %o", msg, this);
    	return this;
    };
    
    //	Sample usage:
    $(root).find('li.source > input:checkbox').log("sources to uncheck").removeAttr("checked");
    

    copy | embed

    0 comments - tagged in  posted by Jonic on Feb 21, 2009 at 2:45 p.m. EST
Sign up to create your own snipts, or login.