ExtendScript: Logging (“Error: Console is Undefined”)

Okay, you have started to write some ExtendScript code to automate all sorts of tedious tasks, but your script isn’t working quite right. You need to debug it! Likely, this process will involve examining the values of certain variables while the script is running.

If this were JavaScript running in a browser, one obvious option that almost all developers will be familiar with is to log the objects of interest using console.log() and to open up the developer tools in the browser of choice to view the output. If this approach is taken for ExtendScript, the following error pops up:

Luckily, there are alternatives. The following code shows three options and I will explain each of them:

#target photoshop
//-----
alert("Logging to Alert Window!"); //<--- Option #1
//-----
$.writeln("Logging to ESTK JavaScript Console!"); //<--- Option #2
//-----
var logFileName = "logfile";
var logFilePath = File($.fileName).path + "/" + logFileName;
var logFile = new File(logFilePath);
logFile.open("w");
logFile.writeln("Logging to logfile!"); //<--- Option #3
logFile.close();
  1. The first option is to use the alert() function. This is simple enough, but it has the annoying side effect of requiring the user to click the OK button with for each usage. For this reason, options 2 and 3 are preferable.

  2. The second option uses the $ object within the ExtendScript ToolKit (ESTK). As described by the ESTK documentation, the $ object “provides a number of debugging facilities and informational methods.” One such method is $.writeln(). This method performs much like console.log() and prints the input to a Console window within ESTK. This is a good option for any logging which does not need to persist beyond the running of the script.

    1. The third option creates a text log file and writes content to it. Usually logging would involve additional capabilities, such as time stamping of each record and setting different debug levels to determine under which circumstances logging statements executed. To keep the example simple, the code does not include those more nuanced aspects of logging.

    Hopefully this post gives to the tools you need to start debugging your ExtendScript code. In the future I will write another post with more advanced logging techniques to provide additional control and utility when producing and working with log files.