summaryrefslogtreecommitdiffstats
path: root/testing/mochitest/tests/SimpleTest/MozillaLogger.js
blob: 07d50572b0cdd5e9b8ce0de099202ffb1c8c5252 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
 * MozillaLogger, a base class logger that just logs to stdout.
 */

"use strict";

function formatLogMessage(msg) {
  return msg.info.join(" ") + "\n";
}

function importMJS(mjs) {
  if (typeof ChromeUtils === "object") {
    return ChromeUtils.importESModule(mjs);
  }
  /* globals SpecialPowers */
  return SpecialPowers.ChromeUtils.importESModule(mjs);
}

// When running in release builds, we get a fake Components object in
// web contexts, so we need to check that the Components object is sane,
// too, not just that it exists.
let haveComponents =
  typeof Components === "object" &&
  typeof Components.Constructor === "function";

let CC = (haveComponents
  ? Components
  : SpecialPowers.wrap(SpecialPowers.Components)
).Constructor;

let ConverterOutputStream = CC(
  "@mozilla.org/intl/converter-output-stream;1",
  "nsIConverterOutputStream",
  "init"
);

class MozillaLogger {
  get logCallback() {
    return msg => {
      this.log(formatLogMessage(msg));
    };
  }

  log(msg) {
    dump(msg);
  }

  close() {}
}

/**
 * MozillaFileLogger, a log listener that can write to a local file.
 * intended to be run from chrome space
 */

/** Init the file logger with the absolute path to the file.
    It will create and append if the file already exists **/
class MozillaFileLogger extends MozillaLogger {
  constructor(aPath) {
    super();

    const { FileUtils } = importMJS("resource://gre/modules/FileUtils.sys.mjs");

    this._file = FileUtils.File(aPath);
    this._foStream = FileUtils.openFileOutputStream(
      this._file,
      FileUtils.MODE_WRONLY | FileUtils.MODE_CREATE | FileUtils.MODE_APPEND
    );

    this._converter = ConverterOutputStream(this._foStream, "UTF-8");
  }

  get logCallback() {
    return msg => {
      if (this._converter) {
        var data = formatLogMessage(msg);
        this.log(data);

        if (data.includes("SimpleTest FINISH")) {
          this.close();
        }
      }
    };
  }

  log(msg) {
    if (this._converter) {
      this._converter.writeString(msg);
    }
  }

  close() {
    this._converter.flush();
    this._converter.close();

    this._foStream = null;
    this._converter = null;
    this._file = null;
  }
}

this.MozillaLogger = MozillaLogger;
this.MozillaFileLogger = MozillaFileLogger;