官术网_书友最值得收藏!

Debugging on the client

In the earlier versions of Socket.IO, debugging was extremely simple. This was because verbose logging was pushed to the developer console by default. Although this feature was a great way to dig into issues when they occurred, it could also get in the way by logging too much when no debugging was needed.

Now, Socket.IO gives us the ability to toggle certain parts of our logging on and off as needed. In this recipe, we will enable client-side debugging to have a better view of what is happening in our Socket.IO communication.

Getting ready

Starting with version 1.0, Socket.IO doesn't show any logging by default. However, it can easily be turned on. Behind the scenes, it will use an NPM module called debug, which allows logging to navigate to various scopes that can be turned on or off as needed.

How to do it…

To enable debugging on the client side, follow these steps:

  1. On the client side, log settings are persisted through HTML5 localStorage, so you can turn logging on by setting the value of localStorage.debug.
  2. To see all the logging messages, just set the value of debug to an asterisk, as shown in the following code:
    localStorage.debug = '*';
  3. Now that robust logging is turned on, you can open your developer tools and see a rich array of messages that details what is happening under the hood:
    How to do it…

How it works…

The localStorage object in the browser is an object with key/value pairs that is maintained when you refresh the page or leave it entirely. It is useful for persisting data on the client side in modern browsers.

Socket.IO uses the debug NPM module. This views the localStorage key to determine the logging level to be displayed in the browser. The fact that the debugging level is set in localStorage can be very useful because you can set a debugging type anywhere even in production, and it will only log on to your machine. Also, you will be able to refresh the page and see the Socket.IO logging from the initial page load, which can be really handy for debugging events that occur earlier on the page life cycle.

There's more…

Not only can you set the logging to show everything, you can also listen for only certain log types by setting them up in localStorage. For example, if you are only interested in XHR requests, you can ask to only see messages in the engine.io-client:polling-xhr namespace with the following code:

localStorage.debug = 'engine.io-client:polling-xhr';

You can also set multiple log types by separating them with a comma, as shown in the following code:

localStorage.debug = 'engine.io-client:polling, engine.io-client:socket';

See also

The following recipe, Debugging on the server.

主站蜘蛛池模板: 石渠县| 揭东县| 五家渠市| 福建省| 海城市| 彰化市| 阳江市| 内丘县| 汉寿县| 阳曲县| 富顺县| 苏尼特左旗| 吉木萨尔县| 商城县| 精河县| 苏尼特右旗| 武鸣县| 乌鲁木齐县| 南汇区| 沙湾县| 辉南县| 岳阳县| 辛集市| 泊头市| 中牟县| 雷州市| 龙陵县| 沙湾县| 横山县| 和龙市| 九台市| 静乐县| 绥芬河市| 登封市| 清丰县| 蒙阴县| 陆河县| 张家川| 宣武区| 策勒县| 惠水县|