How to tail a log with live server clock

At work I have to watch my server’s error log. Good old tail -F /path/to/log runs over SSH all day, every day. Each entry is timestamped. Sometimes those timestamps give me trouble. The age of a timestamp is found by subtracting it from the current time. If I need to know whether the last error occurred 1 minute ago or 61 minutes ago I have to contend with:

  • timestamps in UTC vs. local clock in CST
  • timestamps in 24h vs. local clock in 12h
  • terminal window on second screen vs. clock on main screen
  • daylight savings vs. non-crazy time
  • being at home vs. traveling in other time zones

Finding the age of a timestamp should be simpler than that! So I put a real-time UTC clock in the most convenient place I could find: on the blank line where the next log entry will be written. It refreshes itself every second. Log entries overwrite it and then it reappears again on the new blank line.

The clock on the next line refreshes itself.

The clock on the next line refreshes itself.

Now I can find the age of the last entry without thinking about time zones or daylight savings, without turning my head to check the clock, and without even holding any numbers in my head. Eyeball math. Success!

#!/bin/bash
ssh $1 $(cat <<COMMAND
    while true; do
        echo -ne \`date +"[%d-%b-%Y %H:%M:%S UTC]"\` "\r";
        sleep 1;
    done &
    tail -Fn`tput lines` $2
COMMAND)
echo

If you save this script as st in your path and chmod +x it you can invoke it with st example.com /var/log/file (provided you can ssh example.com and read the file).

I used a few small tricks to compose this solution.

  • the while loop runs in the background (done &)
  • echo -n prints its arguments without a line feed
  • echo -e interprets escape sequences, converting "\r" into a carriage return
  • bonus: `tput lines` passes the local terminal height to tail
  • the final echo gives your prompt a fresh line when you exit with ^C

After SSH connects, the loop starts sending [timestamp]\r to the terminal every second. The carriage return moves the insertion point back to the start of the line without moving it down to the next line. That explains the location of the highlighted character in the image above.

Then tail fills your terminal window with log entries and continues printing new entries as they appear, overwriting the clock. No space wasted, no information lost.

Caveats:

  • log entries must be timestamped and must end in a newline
  • date format is up to you
  • n`tput lines` is optional
  • the clock might draw over log data

That last point is theoretical. It hasn’t been an issue in the two months since I started using this. I also tried to force the clock to overwrite the tail output under abnormal conditions. The only way I could do it was by manually appending to the file without a trailing newline. I guess it depends on the size of the log entries and how they are written. Either way, it’s only terminal output. The log file itself is unmodified.

The script I posted above isn’t exactly what I have been using. It was modified for clarity and generality. I added positional parameters and $(cat <<heredoc) to get clean newlines without having to escape too much. Since I only use this utility to tail one file on one host, the original looks more like this one-liner:

ssh example.com 'while true; do echo -ne `date +"[%d-%b-%Y %H:%M:%S UTC]"`"\r"; sleep 1; done & tail -Fn'`tput lines`' /var/log/file'; echo

Automatically open remote files in local emacs

I prefer to edit text locally in emacs. Most of the files I edit reside on remote servers so I use TRAMP to open remote files locally. What kills me is using emacs remotely via terminal when a shell command invokes $EDITOR (e.g. svn commit). With my new setup, the default editor on the remote machine is my local emacs. I love this.

First, I configure SSH to forward a remote port to my machine. This means that whenever the remote machine tries to connect to itself on that port (localhost:9999) it actually connects to port 9999 on my local OSX machine. I like to keep these details in my ssh_config file (my local ~/.ssh/config):

Host des
User wpdev
ControlMaster auto
ControlPath ~/.ssh/des.sock
RemoteForward 9999 localhost:9999

(I use abbreviated hostnames to save keystrokes. There is a matching entry in my hosts file.)

Second, I configure my local emacs to start the server and copy the server file to the remote host. The server file tells emacsclient how to connect to the server. Adding this to emacs-startup-hook adds a few seconds to my emacs startup time but I rarely start emacs more than once in a day so that’s fine. This is in my local ~/.emacs:

(setq server-use-tcp t
      server-port    9999)
(defun server-start-and-copy ()
  (server-start)
  (copy-file "~/.emacs.d/server/server" "/des:.emacs.d/server/server" t))
(add-hook 'emacs-startup-hook 'server-start-and-copy)

Third, I create a bash script on the remote host which calls emacsclient with the necessary TRAMP path prefixed to its arguments. (If you try running emacsclient remotely without the TRAMP path you’ll get an empty emacs buffer.) Here is the script I put in remote ~/bin/ec and then chmod +x:

#!/bin/bash

params=()
for p in "$@"; do
    if [ "$p" == "-n" ]; then
        params+=( "$p" )
    elif [ "${p:0:1}" == "+" ]; then
        params+=( "$p" )
    else
        params+=( "/ssh:des:"$(readlink -f $p) )
    fi
done
emacsclient "${params[@]}"

Finally, I set up $EDITOR on the remote machine. I also add my bin directory to $PATH so I can invoke ec. This is in my remote ~/.bashrc:

export PATH=~/bin:$PATH
export EDITOR=~/bin/ec

That’s it! More elegant solutions are possible but my new tool is sufficiently sharp and I have work to do!

Python: ISO-8601 year/week from year/month/day

I needed to convert dates to ISO-8601 calendar week and year in a bash script. This is what I came up with:

#!/usr/bin/env python

import optparse
import datetime

parser = optparse.OptionParser()
_, args = parser.parse_args()

y, w, _ = datetime.datetime.strptime(args[0], "%Y/%m/%d").isocalendar()
print "%d/%02d" % (y, w)

It takes input from the command line as YYYY/MM/DD and outputs YYYY/WW.

Copyright Automattic 2012. Public domain where recognized; otherwise Apache 2.0.

1 of 16

1 of 16

A sandwich. A good one.

White Paper Bag

What’s inside?

While in Burlington, Vermont, I worked at the excellent Office Squared downtown coworking space. Some days I had to go out for lunch. That one burrito place on Church Street was unworthy of mention. My next try was Top of the Block Sandwich Shoppe. Here I found my usual.

My first time there, I was overwhelmed by the endless options on the sandwich menu. I didn’t want to spend half my lunch break studying a food list. So I simply asked for a sandwich. Any sandwich would do, I said, as long as it’s good. No, I don’t have any food allergies or restrictions. Just make it a sandwich, not a wrap. Surprise me.

This intrigued the young ladies behind the counter. The lucky one who got to make my sandwich was thrilled by the possibilities. She could make whatever she fancied and I would probably love it. The others kept an eye on the project, jealous of her creative opportunity.

I took my sandwich back to the office and I loved it. The bread, the special mayo, the juicy meat and unconventional mix of veggies. This was a unique sandwich made by a person whose curiosity and passion had been aroused by a simple, open-minded request: make me a sandwich. A good one.

Each week I went back once or twice for a new sandwich. Each visit brought smiles to the faces behind the counter. Each sandwich was better than my memory of the last.

By the third visit I didn’t have to speak my order. My request was so memorable that I was an instant regular. I am the guy who wants a random sandwich. Surprise me.

My surprise sandwich was the most consistently pleasurable lunch outside of my home. For the same price everyone else paid for their made-to-order sandwich I got joy, suspense, and possibly the best sandwich made that day.

When ordering a sandwich what I really want is two slices of bread surrounding something good. Turkey, peppers, mustard, none of the above, whatever. Maybe not every sandwich maker has the passion or the sense of humor to do it right like Top of the Block. Maybe I’d be unhappy with the “surprise item” from most other places. I’m happy I found these professionals and took that chance.

Follow

Get every new post delivered to your Inbox.

Join 1,657 other followers