Cookbook: Dated logging

sohamLTD edited this page Dec 14, 2016 · 2 revisions

The following requires IPython >= 0.13.

The following startup file creates a dated log file of all input and output in the log folder of the given profile. If the file already exists, it appends to it, writing a time stamp indicating the creation of a new session.

This code is an adaptation to IPython 0.12 of a similar logging setup floating around on the internet.

Put in a file 05_log.py in the startup/ directory of your profile. For example, ~/.ipython/profile_default/startup/05_log.py:

from time import strftime
import os.path

ip = get_ipython()

ldir = ip.profile_dir.log_dir 
fname = 'log-' + ip.profile + '-' + strftime('%Y-%m-%d') + ".py"
filename = os.path.join(ldir, fname)
notnew = os.path.exists(filename)

try:
  ip.magic('logstart -o %s append' % filename)
  if notnew:
      ip.logger.log_write(u"# =================================\n")
  else:
      ip.logger.log_write(u"#!/usr/bin/env python\n" )
      ip.logger.log_write(u"# " + fname + "\n" )
      ip.logger.log_write(u"# IPython automatic logging file\n" )
  ip.logger.log_write(u"# " + strftime('%H:%M:%S') + "\n" )
  ip.logger.log_write(u"# =================================\n" )
  print (" Logging to "+filename)
except RuntimeError:
    print (" Already logging to "+ip.logger.logfname)

Now whenever you start a session with ipython --profile=default a session log will be stored in ~/.ipython/profile_default/log/log-default-DATE.py.

Clone this wiki locally
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.