logging snippets

How to add logging to CakePHP applications

Tagged php, cakephp, logging, debug  Languages php

Note that Pear's Logging package is a lot more flexible, so I recommend you use that instead of CakePHP's built-in logging.

Use this code to add a debug message to the CakePHP debug log:

$this->log("Upload action accessed", LOG_DEBUG);

Note that using something other than LOG_DEBUG will log the message as an error.

Run the code once and you should be able to see the message in $CAKE_APP/tmp/logs/debug.log.

Logging to a file with Elixir

Tagged elixir, file, logging  Languages elixir

mix.exs:

  def application do
    [
      applications: [:logger, :logger_file_backend, ...],
      mod: {Snippets, []}
    ]
  end

  def deps do
    [
      {:cowboy, "~> 1.0.0"}, # web server
      {:logger_file_backend, "~> 0.0.7"} # writes log messages to a file, LOL
      ....
    ]
   end

config/dev.exs:

config :logger, :error_log,
  path: "log/app.log",
  level: :debug

A simple log wrapper for Go

Tagged go, log, logging  Languages go

Version 1

This is a simple log wrapper for go’s built in log package. Put the following code in a file named log.go:

package main

import (
    golog "log"
    "os"
)

//
// Use ioutil.Discard instead of f to send log to '/dev/null'
//
type Logger struct {
    Info     *golog.Logger
    Error    *golog.Logger
    Debug    *golog.Logger
    FatalLog *golog.Logger
}
func (logger Logger) Fatal(format string, args ...interface{}) {
    logger.FatalLog.Printf(format, args...)
    golog.Fatalf(format, args...)
}

var logFile *os.File
var log Logger

func init() {
    fileName := os.Getenv("LOG")
    if len(fileName) > 0 {
        var err error
        logFile, err = os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
        if err != nil {
            golog.Fatalf("error opening file: %v", err)
        }
    } else {
        logFile = os.Stdout
    }
    log.Info = golog.New(logFile, "INFO  ", golog.LstdFlags)
    log.Error = golog.New(logFile, "ERROR ", golog.LstdFlags)
    log.Debug = golog.New(logFile, "DEBUG ", golog.LstdFlags)
    log.FatalLog = golog.New(logFile, "FATAL ", golog.LstdFlags)
}

Example:

log.Info.Printf("Notifications %v", notifications)
log.Debug.Printf("Notifications %v", notifications)

Version 2

To remove the call to Printf you could do this:

type Log struct {
...
    //Info     *golog.Logger
    Info     func(string, ...interface{})
...
}

func init() {
...
    log.Info = golog.New(logFile, "INFO  ", golog.LstdFlags).Printf
...
}

Now you can simply call log.Info:

log.Info("Notifications %v", notifications)
log.Debug("Notifications %v", notifications)

See https://golang.org/pkg/log/#Logger