Quite a few solutions exist for taking a backup of your IMAP account, but they were designed with IMAP folders in mind.
Any of them will work for Gmail too, but due to the semantic difference Between Gmail labels and standard IMAP folders, a message will be backed up once for each label it has: a huge waste of disk space if you, like us, use often multiple labels on a single email.
Our approach is extremely simple: every email gets saved in a single local directory (path_to_app/gmail/MailStore/ by default). The original structure of your accounts (yes, multiple accounts are supported!) is stored in the same directory, inside a SQLite database (named gmail.db by default) where we also store the state of our last backup.