Monitoring in X11 (Graphical Desktop) Session Only
In you're using the XInput layer (you probably are, if you're running a modern X) then
xinput test «keyboard-id» will give pey press and release events. You can get the keyboard ID by running
xinput list. You can also use the name.
xinput test 'AT Translated Set 2 keyboard' | grep -c 'key press'
Note that when you pipe
xinput, it has a fairly large buffer. So you may lose some keystrokes, unfortunately. You could use the XI2 API directly to avoid that, but that's not easy from shell.
You can fairly easily start your script as one of the login scripts in your desktop environment or from your
.xsession file, depending. The
xinput should exit when you log out, because it'll lose its X11 connection. So it's really easy to track when your session starts and ends.
Monitoring System-wide (All Sessions, Even Text Mode)
Alternatively, if you want to monitor all keystrokes on the system, not just those in your X11 session, you can use the
input-events (part of the input-utils package on Debian, at least). This must run as root. Use
lsinputs to find the right input device (happens to be 0 on my system) and then:
input-events 0 | grep -c 'EV_KEY.*pressed'
If you go this way, you'll have to figure out when your sessions start and end some way (e.g., peterph's dbus suggestion).