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

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.

主站蜘蛛池模板: 方山县| 阳曲县| 梅州市| 新宾| 文水县| 临夏市| 普宁市| 祥云县| 宁南县| 荥经县| 砚山县| 江津市| 鹰潭市| 曲水县| 珲春市| 达州市| 治县。| 绥棱县| 什邡市| 河津市| 福贡县| 二连浩特市| 石阡县| 珲春市| 甘洛县| 宣威市| 岢岚县| 会昌县| 江都市| 浦北县| 涞源县| 苍山县| 荔浦县| 耿马| 平陆县| 潼关县| 东港市| 沅陵县| 钟祥市| 祁阳县| 西盟|