How do I detect when the system suspends?

I need to be able to log the times that an Ubuntu 10.04 Desktop system is suspended and resumed.

I can detect when the system is resumed via a DBus signal (org.freedesktop.UPower.Resuming()) but the corresponding "org.freedesktop.UPower.Sleeping()" signal is never fired. Ideally, I'd like to use DBus, but given the lack of success I'm having, I'd be happy with any solution providing it can be called from the command line.

I've discovered one way to do it:

tail -f /var/log/pm-suspend.log | grep "performing suspend"

This simply listens on one of the pm logs for the suspend logging. Although this works, it's probably rather brittle. I've found relying on log parsing to be rather problematic in the past due to changes in the log statements.

Ideally I'd like a more robust mechanism. The service that invokes this will be ran as root.


Try putting the following in /etc/pm/sleep.d. This should be independent of whether your machine uses APM or ACPI.

#!/bin/sh

LOGFILE="/var/log/sleep.log"

case "$1" in
        resume)
                echo "Resumed from suspend at `date`" >> "$LOGFILE"
                ;;
        thaw)
                echo "Resumed from hibernation at `date`" >> "$LOGFILE"
                ;;
        suspend)
                echo "Suspended to ram at `date`" >> "$LOGFILE"
                ;;
        hibernate)
                echo "Hibernated to disk at `date`" >> "$LOGFILE"
                ;;
esac

A few other options that may work on more modern systems are:

cat /var/log/syslog | grep 'systemd-sleep' which will display system suspensions and resumes with timestamps.

or

journalctl | grep suspend which will display also display suspensions and resumes with timestamps. The suspends here will look something like PM: suspend entry (s2idle) and the resumes will look like suspend exit.