plain-text.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. module.metadata = {
  6. "stability": "unstable"
  7. };
  8. const { Cc, Ci, Cu, Cr } = require("chrome");
  9. const self = require("../self");
  10. const prefs = require("../preferences/service");
  11. const { merge } = require("../util/object");
  12. const { ConsoleAPI } = Cu.import("resource://gre/modules/devtools/Console.jsm");
  13. const DEFAULT_LOG_LEVEL = "error";
  14. const ADDON_LOG_LEVEL_PREF = "extensions." + self.id + ".sdk.console.logLevel";
  15. const SDK_LOG_LEVEL_PREF = "extensions.sdk.console.logLevel";
  16. let logLevel = DEFAULT_LOG_LEVEL;
  17. function setLogLevel() {
  18. logLevel = prefs.get(ADDON_LOG_LEVEL_PREF,
  19. prefs.get(SDK_LOG_LEVEL_PREF,
  20. DEFAULT_LOG_LEVEL));
  21. }
  22. setLogLevel();
  23. let logLevelObserver = {
  24. QueryInterface: function(iid) {
  25. if (!iid.equals(Ci.nsIObserver) &&
  26. !iid.equals(Ci.nsISupportsWeakReference) &&
  27. !iid.equals(Ci.nsISupports))
  28. throw Cr.NS_ERROR_NO_INTERFACE;
  29. return this;
  30. },
  31. observe: function(subject, topic, data) {
  32. setLogLevel();
  33. }
  34. };
  35. let branch = Cc["@mozilla.org/preferences-service;1"].
  36. getService(Ci.nsIPrefService).
  37. getBranch(null);
  38. branch.addObserver(ADDON_LOG_LEVEL_PREF, logLevelObserver, true);
  39. branch.addObserver(SDK_LOG_LEVEL_PREF, logLevelObserver, true);
  40. function PlainTextConsole(print) {
  41. let consoleOptions = {
  42. prefix: self.name + ": ",
  43. maxLogLevel: logLevel,
  44. dump: print
  45. };
  46. let console = new ConsoleAPI(consoleOptions);
  47. // As we freeze the console object, we can't modify this property afterward
  48. Object.defineProperty(console, "maxLogLevel", {
  49. get: function() {
  50. return logLevel;
  51. }
  52. });
  53. // We defined the `__exposedProps__` in our console chrome object.
  54. // Although it seems redundant, because we use `createObjectIn` too, in
  55. // worker.js, we are following what `ConsoleAPI` does. See:
  56. // http://mxr.mozilla.org/mozilla-central/source/dom/base/ConsoleAPI.js#132
  57. //
  58. // Meanwhile we're investigating with the platform team if `__exposedProps__`
  59. // are needed, or are just a left-over.
  60. console.__exposedProps__ = Object.keys(ConsoleAPI.prototype).reduce(function(exposed, prop) {
  61. exposed[prop] = "r";
  62. return exposed;
  63. }, {});
  64. Object.freeze(console);
  65. return console;
  66. };
  67. exports.PlainTextConsole = PlainTextConsole;