With one line of code, BetterLog extends the native apps script Logger and gives you automatic additional features like logging to a spreadsheet and more.
This library is already published as an Apps Script, making it easy to include in your project. To add it to your script, do the following in the Apps Script code editor:
- Click on the menu item "Resources > Libraries..."
- In the "Find a Library" text box, enter the project key
MYB7yzedMbnJaMKECt6Sm7FLDhaBgl_dE
and click the "Select" button. - Choose a version in the dropdown box (usually best to pick the latest version).
- Click the "Save" button.
Alternatively, you can copy and paste the Code.gs file directly into your script project.
// Add one line to use BetterLog
Logger = BetterLog.useSpreadsheet('your-spreadsheet-key-goes-here');
//Now you can log and it will also log to the spreadsheet
Logger.log("That's all you need to do");
Any logs you generate are automatically copied and rolled over once they reach 50,000 lines so you'll always have a full history of log events.
With some good error handling you can catch and log stack traces:
function myFunction() {
try {
// Add one line to use BetterLog and log to a spreadsheet
Logger = BetterLog.useSpreadsheet('your-spreadsheet-key-goes-here');
//Now you can log and it will also log to the spreadsheet
Logger.log("That's all you need to do");
//Do more logging
for (var i = 0; i < 5; i++) {
var processingMessage = 'Processing ' + i;
Logger.finest('This is inside my loop. i is %s', i );
}
//We're done
Logger.log('The loop is done and i is now %s', i );
} catch (e) { //with stack tracing if your exceptions bubble up to here
e = (typeof e === 'string') ? new Error(e) : e;
Logger.severe('%s: %s (line %s, file "%s"). Stack: "%s" . While processing %s.',e.name||'',
e.message||'', e.lineNumber||'', e.fileName||'', e.stack||'', processingMessage||'');
throw e;
}
}
Errors can be displayed with stacktraces:
##Tips & Tricks
You can change the message layout:
Logger.DATE_TIME_LAYOUT = "''"; //ref http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Logger.log('Look no timestamp!');
Error: Not enough arguments (line 134, file "Code", project "BetterLog")
This can happen if you call the log method without enough arguments. For example, this will cause the error:
Logger.log("Test 1 2 %s")
whereas this won't cause the error:
Logger.log("Test 1 2 %s", "three")
- BetterLog currently can't be used to log from custom functions in Google Sheets because custom functions are run in the context of an anononymous user which means that BetterLog will not be able to edit the spreadsheet to create or append to a log sheet. I'm not aware of a workaround but you could write a web app whose URL could be called anonymously with a query parameter that is written to your log.