Dealing with console logging/IE problems

As you may now putting console.log (or .error or .info...) into a javascript will stop the script working in most versions of Internet Explorer unless the debugger ("f12 tool") is open, except possibly version 11.

I wrote this simple Python script to scan a directory structure and comment out any references to console.[log,error,info,warn]:

import os
import re

def walk(rootpath, fix=False):
    goodones = re.compile("^.*//.*console\..*")
    for root, dirs, files in os.walk(rootpath):
        for filename in files:
            if root.startswith("js/libs"):
            name, ext = os.path.splitext(filename)
            fullname = os.path.join(root, filename)
            if ext == ".js":
                content = open(fullname,"r").read().split("\n")
                writeback = False
                for i in range(len(content)):
                    if goodones.match(line):
                        cdlok += 1
                        cdlfound += 1
                    elif any([x in line for x in "console.log","",
                                                 "console.error", "console.warn"]):
                        cdlbad += 1
                        cdlfound += 1
                        if fix:
                            line = line.replace("console.","//console.")
                            content[i] = line
                            writeback = True
                if writeback:
                    cdlfixed += 1
    fmt = "%15s %d"
    print fmt%("Found:",cdlfound)
    print fmt%("OK:",cdlok)
    print fmt%("Bad:",cdlbad)
    print fmt%("Fixed:",cdlfixed)

if __name__ == "__main__":
    walk("js", True)

I'm not saying its perfect, or that it won't break your code, so do test stuff before you commit to your source control.

The line "if root.startswith('js/libs'):" makes sure we dont mess with files in the libs directory (a bit of a hack but there you are!) because thats where compressed and minified libraries like JQuery etc are which will break bad if I fiddle with the code.

Version 3 updated May 13, 2014, 3:27 p.m.