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

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.

主站蜘蛛池模板: 平和县| 海盐县| 二连浩特市| 英超| 遂昌县| 宜兰县| 张家界市| 安徽省| 江源县| 安西县| 克山县| 文山县| 阿荣旗| 资阳市| 察哈| 阿勒泰市| 岳西县| 饶阳县| 沧州市| 叶城县| 高邮市| 东安县| 陕西省| 深圳市| 揭东县| 嵩明县| 宽甸| 商洛市| 万山特区| 平乐县| 岳西县| 米林县| 南京市| 柳江县| 衡阳市| 洮南市| 潜江市| 阳城县| 永宁县| 资源县| 牟定县|