<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Garvitgulati on Medium]]></title>
        <description><![CDATA[Stories by Garvitgulati on Medium]]></description>
        <link>https://medium.com/@garvitgulati47?source=rss-523f4e7f1069------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*a1kfKay0UQcClwuT</url>
            <title>Stories by Garvitgulati on Medium</title>
            <link>https://medium.com/@garvitgulati47?source=rss-523f4e7f1069------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:13:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@garvitgulati47/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Application Monitoring with NodeJs , prometheus, Winston, Open telemetry and Grafana cloud-4…]]></title>
            <link>https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-4-4e4b34d814cc?source=rss-523f4e7f1069------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e4b34d814cc</guid>
            <dc:creator><![CDATA[Garvitgulati]]></dc:creator>
            <pubDate>Wed, 26 Oct 2022 18:10:28 GMT</pubDate>
            <atom:updated>2022-10-27T10:33:15.229Z</atom:updated>
            <content:encoded><![CDATA[<h3>Application Monitoring with NodeJs , prometheus, Winston, Open telemetry and Grafana cloud-4 [Setting up traces]</h3><p>In the last two posts, I talked about setting up logging for our nodeJs server with winston and promtail ( <a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-2-71432ac1ec6b">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-2-71432ac1ec6b</a> ) and collecting metrics about our server using prometheus ( <a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-3-b8cba6210535">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-3-b8cba6210535</a> ) view them on the Grafana cloud dashboard.</p><p>Coming to an end of the series, this will the final post where we will be collecting traces from our server using opentelemetry libraries and viewing them on, yes you guessed it right, Grafana dashboard.</p><p>We will be using the same server we set up in prerequisites. Please read this post before starting with this post to avoid any errors: <a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-e2fddcb7698d">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-e2fddcb7698d</a>.</p><p>So, let’s get started.</p><h3>What are traces?</h3><p>Suppose you make a request to the server. While processing that request, server makes 2–3 queries to the DB and calls additional functions in the request. Now, a number of requests are failing and we want to identify the root cause which function or DB query is causing trouble. Or the request is taking too long to respond and we want to identify which part is responsible. How to do this?</p><p>You can set up logging print statements but that would be a lot of hassle for all the requests. This is where traces help. A trace of a request will collect data about all the processing done and will provide you insights like, but not limited to, execution time, function called etc. Each of the single execution in the trace is called a span.</p><p>In technical terms,</p><blockquote>A trace is a collection of operations that represents a unique transaction handled by an application and its constituent services. A span represents a single operation within a trace.</blockquote><p>What all information they collect depends on the tracer used and how it is configured.</p><p>In this post, we will be using opentelemetry to collect traces and spans and use otlp collector to send the traces to Grafana in order to view them.</p><p>Let us understand the tech stack before jumping to implementation:</p><h3>Opentelemetry</h3><p>OpenTelemetry is <strong>an open source observability framework</strong>. It offers vendor-agnostic or vendor-neutral APIs, software development kits (SDKs) and other tools for collecting telemetry data from cloud-native applications and their supporting infrastructure to understand their performance and health.</p><p><strong>Simply, it’s a tool that helps us collect(here) trace information from our application and export it.</strong></p><p>Read about it in detail: <a href="https://opentelemetry.io/docs/concepts/what-is-opentelemetry/">https://opentelemetry.io/docs/concepts/what-is-opentelemetry/</a></p><h3>Opentelemetry Collector</h3><p>The OpenTelemetry Collector is a vendor-agnostic proxy that can receive, process, and export telemetry data. It supports receiving telemetry data in multiple formats (e.g., OTLP, Jaeger, Prometheus, as well as many commercial/proprietary tools) and sending data to one or more backends.</p><p>Read about it at: <a href="https://opentelemetry.io/docs/concepts/components/#collector">https://opentelemetry.io/docs/concepts/components/#collector</a></p><p>AND THAT’S ALL WITH THE CONCEPTS.</p><p>Let’s begin with implementation.</p><h3>Setting up Grafana Cloud</h3><p>This post assumes that you have already created a grafana cloud account. Please read the configure grafana cloud steps from the second post if you face any difficulty navigating between different screens.</p><ol><li>Login to your grafana account, scroll down and click on send traces under Grafana Tempo.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9uo6JdKhkPgF_12SP0nDg.png" /></figure><p>2. Click on Generate Now to generate a new API key or if you have an already generated key (probably from the previous post), you can reuse that. Skip to next section in that case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBV8SUW-o6b_6ysqHQ-Lng.png" /></figure><p>3. Give the API key a name and select MetricsPublisher as role. Save the generated API key somewhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yPeAO5fsfz1qs_iK9BSiw.png" /></figure><p>4. Open terminal in your PC and run the command: echo -n &lt;user&gt;:&lt;API KEY&gt; | base64 and copy the output. This hashed key will be used for authentication.</p><h3>Setting up opentelemetry collector</h3><p>We will be adding another container for collecting and exporting traces to our grafana cloud.</p><ol><li>Go to the directory where your docker-compose file is located and create a new file in the same directory titled “otel-config.yml”. Paste the following code in it:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bdb85798d0f117ef6e8596dbdaae47c/href">https://medium.com/media/9bdb85798d0f117ef6e8596dbdaae47c/href</a></iframe><p>2. Now go to the docker-compose.yml file and add another container with the given configuration. <strong>Make sure to keep the name of the config file same as the one provided in volumes.</strong></p><pre>collector:</pre><pre>image: otel/opentelemetry-collector:0.23.0</pre><pre>command: &#39;--config /etc/otel-config.yaml&#39;</pre><pre>volumes:</pre><pre>- ./otel-config.yml:/etc/otel-config.yaml</pre><pre>ports:</pre><pre>- 14268:14268</pre><pre>expose:</pre><pre>- 14268</pre><pre>networks:</pre><pre>- monitoring</pre><p>finally, the compose file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8234ba97e2626dad576371e7bb7390c/href">https://medium.com/media/f8234ba97e2626dad576371e7bb7390c/href</a></iframe><p>And our collector is ready, Only thing left is to export the traces.</p><h3>Exporting the traces</h3><ol><li>Run npm install to install the required packages</li></ol><pre>npm install opentelemetry-instrumentation-express <a href="http://twitter.com/opentelemetry/instrumentation-mongodb">@opentelemetry/instrumentation-mongodb</a> <a href="http://twitter.com/opentelemetry/instrumentation-http">@opentelemetry/instrumentation-http</a> <a href="http://twitter.com/opentelemetry/sdk-trace-node">@opentelemetry/sdk-trace-node</a> <a href="http://twitter.com/opentelemetry/sdk-node">@opentelemetry/sdk-node</a> <a href="http://twitter.com/opentelemetry/api">@opentelemetry/api</a> <a href="http://twitter.com/opentelemetry/exporter-jaeger">@opentelemetry/exporter-jaeger</a></pre><p>2. Create a new file called ‘tracing.js’ and paste the following code:</p><blockquote>Note: I have packages to instrument mongodb calls as well, although it is not used here. Since mostly people require it, I have added the configuration so as to save them trouble.</blockquote><p>Make sure the endpoint has the name of the container same as you set up in the docker-compose file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9721ea660801ba59da83e423e1ff86c2/href">https://medium.com/media/9721ea660801ba59da83e423e1ff86c2/href</a></iframe><p>3. Go to the index.js file and add the following line at the top:</p><pre>const tracer = require(&quot;./tracing&quot;)(&quot;Service Name&quot;);</pre><p>And done, you are now exporting traces from your app.</p><p>Run $docker-compose build in your terminal to make the changes to the container as well.</p><h3>Viewing Traces</h3><ol><li>Run $docker-compose up to run your containers</li><li>Go to your stack (where you accessed send traces) and click on launch under Grafana.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*18x9rHjVejL0jexT.png" /></figure><p>5. From the left panel select Explore</p><p>6. Under sources select the tempo source</p><p>7. Select the search option and under service name drop down select the name you set up in index.js file [refresh the page if it’s not there]</p><blockquote><em>It may take some time for traces to appear (wait for 3–4 mins)</em></blockquote><p>8. Run query from top right corner</p><p>9. Click on a trace ID to see the spans and detailed info</p><p>REFERENCE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwoxtU_pknxIqezHO7c0lQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYmT8c-utzyAUQ9Q-hzFYQ.png" /></figure><p>And done. With this we have successfully set up an application monitoring system for our express server. You can deploy this server on any platform and get the insights on your grafana cloud dashboard.</p><p>You can find the code for the whole blog at: <a href="https://github.com/garvit170/Application-Monitoring-with-NodeJs/tree/852265747adf91f2539e5d2a321e8743521e7ced">https://github.com/garvit170/Application-Monitoring-with-NodeJs/tree/dc6765781665d8ce3b06e4c5ac0bd174fe38a70f</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e4b34d814cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Application Monitoring with NodeJs , prometheus, Winston, Open telemetry and Grafana cloud-3…]]></title>
            <link>https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-3-b8cba6210535?source=rss-523f4e7f1069------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8cba6210535</guid>
            <category><![CDATA[monitoring-tools]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Garvitgulati]]></dc:creator>
            <pubDate>Mon, 24 Oct 2022 09:42:11 GMT</pubDate>
            <atom:updated>2022-10-26T18:16:01.027Z</atom:updated>
            <content:encoded><![CDATA[<h3>Application Monitoring with NodeJs , prometheus, Winston, Open telemetry and Grafana cloud-3 [Setting up metrics]</h3><p>In the last post, I talked about setting up logging for our nodeJs server with winston and promtail and view them on the grafana cloud dashboard. Read it at: <a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-2-71432ac1ec6b">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-2-71432ac1ec6b</a></p><p>We will be using the same server we set up in prerequisites. Please read this post before starting with this post to avoid any errors: <a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-e2fddcb7698d">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-e2fddcb7698d</a>.</p><p>Today, we will be setting up metrics collection for our server. By metrics, I mean we will be collecting information about total number of requests on each route, response time, metrics about CPU usage, node js event loop etc.</p><p>Tech Stack: Prometheus + express-prometheus-middleware + grafana cloud</p><p>For this we will be using prometheus (an open source tool for monitoring). We will come to this in detail after the flow of data. So we will expose metrics from our server on ‘/metrics’ route, don’t worry we have a npm package(express-prometheus-middleware) for this which will do this for us with very small amount of codes. Prometheus will scrape this ‘/metrics’ route and collect the metrics uploading them to our grafana dashboard.</p><p>Let us understand everything one by one.</p><h3>Prometheus</h3><p><a href="https://github.com/prometheus">Prometheus</a> is an open-source systems monitoring and alerting toolkit originally built at <a href="https://soundcloud.com/">SoundCloud</a>. Since its inception in 2012, many companies and organizations have adopted Prometheus, and the project has a very active developer and user <a href="https://prometheus.io/community">community</a>. It is now a standalone open source project and maintained independently of any company.</p><p>Prometheus collects and stores its metrics as time series data, i.e. metrics information is stored with the timestamp at which it was recorded, alongside optional key-value pairs called labels.</p><p>In layperson terms, <em>metrics</em> are numeric measurements. <em>Time series</em> means that changes are recorded over time. What users want to measure differs from application to application. For a web server it might be request times, for a database it might be number of active connections or number of active queries etc.</p><p>Metrics play an important role in understanding why your application is working in a certain way. Let’s assume you are running a web application and find that the application is slow. You will need some information to find out what is happening with your application. For example the application can become slow when the number of requests are high. If you have the request count metric you can spot the reason and increase the number of servers to handle the load.</p><p>You can read about prometheus in detail at: <a href="https://prometheus.io/docs/introduction/overview/">https://prometheus.io/docs/introduction/overview/</a></p><h3>Express-Prometheus-Middleware</h3><blockquote>This is a middleware for express servers, that expose metrics for prometheus.</blockquote><blockquote>The metrics exposed allows to calculate common RED (Request, Error rate, Duration of requests), and USE (Utilisation, Error rate, and Saturation), metrics</blockquote><p>This middleware provides a lot of the metrics out of the box saving us the trouble of defining our own counters and other prometheus metrics. You can read about all the metrics here: <a href="https://github.com/joao-fontenele/express-prometheus-middleware#metrics-exposed">https://github.com/joao-fontenele/express-prometheus-middleware#metrics-exposed</a></p><p>To read about this package: <a href="https://github.com/joao-fontenele/express-prometheus-middleware#express-prometheus-middleware">https://github.com/joao-fontenele/express-prometheus-middleware#express-prometheus-middleware</a></p><h3>Grafana Cloud</h3><p>And at last, we will be again utilizing grafana cloud as a dahsboard to display our collected metrics. You can read about it in the previous post or at <a href="https://grafana.com/products/cloud/?plcmt=nav-products-cta1&amp;cta=cloud">https://grafana.com/products/cloud/?plcmt=nav-products-cta1&amp;cta=cloud</a>.</p><p>Let’s get started with the implementation.</p><h3>Configure Grafana cloud</h3><p>This post assumes that you have already created a grafana cloud account. Please read the configure grafana cloud steps from the previous post if you face any difficulty navigating between different screens.</p><ol><li>Login to your grafana account and click on send metrics (it will be beside the send logs button you clicked on in the previous post[link in the beginning of this post])</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAcFdZakkRSPbwn7689RbQ.png" /></figure><p>2. Scroll down to password/ API key section and click on “Generate now”.</p><p><strong>NOTE: You can use your already generated API key (if you followed the previous tutorial you can utilize the same key). If you are using a pre generated API key skip to step 4.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kWSQQmoHL4fB1LtHv2J4A.png" /></figure><p>3. Give the API key a name and select MetricsPublisher as role.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odNSAq1eJTp3RGsGiwwtkw.png" /></figure><p>4. Save this API key. Scroll down and copy the remote_write code and save it somewhere. We will be utilising this while configuring the prometheus next. Don’t forget to replace your API key here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtmJO56PTpCw50eMxq9Kiw.png" /></figure><h3>Set up prometheus</h3><ol><li>Go to your working directory (the one where we set up the nodeJS server in the first post).</li><li>Create a new file titled “prometheus-config.yml” and paste the following code.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e28950b59bac34796273a1b0aeeefa54/href">https://medium.com/media/e28950b59bac34796273a1b0aeeefa54/href</a></iframe><p>Make sure the target is same as “name-of-your-server-container:port-used”</p><p>You can change job name to whatever you like</p><p>Replace line 8–12 with your code generated in step 4 of configure grafana cloud.</p><p>3. Now go to the docker-compose file. And add a new container for prometheus. Finally the code should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d76e47cb63b9b9e7dd99adb762d27c0/href">https://medium.com/media/8d76e47cb63b9b9e7dd99adb762d27c0/href</a></iframe><p>Now, we have a prometheus container to scrape metrics which is configured for our use case, it’s time to start exposing metrics.</p><h3>Exposing Metrics from server</h3><p>As mentioned in the beginning, we will be using express-prometheus-middleware to expose metrics from our server. So let’s start by setting up.</p><ol><li>Go to terminal and run $npm i express-prometheus-middleware. Make sure you are in the same directory as your server.</li><li>Go to index.js and add the following code in the file</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f743caea02419166bafd20ac8ebbf9d0/href">https://medium.com/media/f743caea02419166bafd20ac8ebbf9d0/href</a></iframe><p>and done we are now exposing our metrics. To verify, start the server and go to /metrics.</p><h3>Running and viewing your metrics</h3><ol><li>Build your container by running $docker-compose build.</li><li>Start the container by running $docker-compose up</li><li>Go to localhost:4500 and hit 3–4 routes.</li></ol><p>4. Go to your stack (where you accessed send metrics) and click on launch under Grafana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UlgxZyj4JyFkaDX4.png" /></figure><p>5. From the left panel select Explore</p><p>6. Under sources select the prometheus source</p><p>7. Use builder to write a query with the drop downs or the use the one from image</p><blockquote>It may take some time for prometheus metrics to appear (wait for 3–4 mins)</blockquote><p>8. Run query from top right corner</p><p>Reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7mc6ckMzd5Li3tStm7osA.png" /></figure><p>And you can see the total number of requests metrics for the route. Play around with all the metrics.</p><p>You can find the complete code used in this blog at: <a href="https://github.com/garvit170/Application-Monitoring-with-NodeJs/tree/3e007b5c25099b6f708c1e9e44ec85b114b19d24">https://github.com/garvit170/Application-Monitoring-with-NodeJs/tree/3e007b5c25099b6f708c1e9e44ec85b114b19d24</a></p><p>Next post: <a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-4-4e4b34d814cc">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-4-4e4b34d814cc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8cba6210535" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Application Monitoring with NodeJs , prometheus, Winston, Open telemetry and Grafana cloud-2…]]></title>
            <link>https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-2-71432ac1ec6b?source=rss-523f4e7f1069------2</link>
            <guid isPermaLink="false">https://medium.com/p/71432ac1ec6b</guid>
            <category><![CDATA[grafana-loki]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[logging-and-monitoring]]></category>
            <category><![CDATA[winston]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Garvitgulati]]></dc:creator>
            <pubDate>Wed, 12 Oct 2022 09:17:20 GMT</pubDate>
            <atom:updated>2022-10-26T18:15:36.580Z</atom:updated>
            <content:encoded><![CDATA[<h3>Application Monitoring with NodeJs , prometheus, Winston, Open telemetry and Grafana cloud-2 [Setting up Logging]</h3><p>In the previous, post I talked about setting up a sample express server with docker. Please read this post before starting with this post to avoid any errors: <a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-e2fddcb7698d">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-e2fddcb7698d</a></p><p>In this post, we will set up logging system to collect our logs and display them on a Grafana dashboard.</p><p>Our overflow will be:</p><ol><li>Our server will generate a “server.log” file using the winston logger (npm package).</li><li>This log file will be monitored by promtail.</li><li>Promtail will ship the contents of this file to Grafana Loki of our Grafana cloud where we can see these logs.</li></ol><p>If you don’t understand this, don’t worry just keep on reading and things will start making sense slowly.</p><p>Let us understand a little about the tools we will be using:</p><ol><li><strong>Winston:</strong> winston is designed to be a simple and universal logging library with support for multiple transports. A transport is how you want to see the logs: on console or on a file or on multiple files. Winston logger has different levels of logging: <a href="https://www.npmjs.com/package/winston#logging-levels">https://www.npmjs.com/package/winston#logging-levels</a>. We will be using only info, warn, and error but you can use as per your use case. You can read more about winston at <a href="https://www.npmjs.com/package/winston">https://www.npmjs.com/package/winston</a> or read <a href="https://www.section.io/engineering-education/logging-with-winston/">https://www.section.io/engineering-education/logging-with-winston/</a></li><li><strong>Promtail: </strong>Promtail is an agent which ships the contents of local logs to a private Grafana Loki instance or <a href="https://grafana.com/oss/loki">Grafana Cloud</a>. Imagine it like a service reading your log file and uploading all your logs to grafana instance where you can see the logs. Read about it at: <a href="https://grafana.com/docs/loki/latest/clients/promtail/">https://grafana.com/docs/loki/latest/clients/promtail/</a>.</li><li><strong>Grafana Cloud: </strong>Grafana Cloud is a composable observability platform, integrating metrics, traces and logs with Grafana. It’s an online dashboard so that we can see our logs from anywhere. Read more at <a href="https://grafana.com/products/cloud/?plcmt=nav-products-cta1&amp;cta=cloud">https://grafana.com/products/cloud/?plcmt=nav-products-cta1&amp;cta=cloud</a></li></ol><p>So let’s get started.</p><h3>Adding Winston Logger to our server</h3><ol><li>Install winston package from npm by running $ npm install winston in the terminal with our sample express server directory as the current working directory.</li><li>Create a new file named logger.js and paste the following code:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f756594ee2f3a97b802fdc704018fcd1/href">https://medium.com/media/f756594ee2f3a97b802fdc704018fcd1/href</a></iframe><p>In this file we initialise a logger with winston’s createLogger function. Inside we define our winston console transport to show our logs on our console. And then check for the ‘/logs’ directory and if it exists, we will add another transport to our logger for writing our logs. Incase a server.log file doesn’t exist winston will create a new one for us.</p><blockquote>Focus on the logs directory path which is /logs, this is not a path in our system but a path for a docker volume which we defined and mounted in our web container with the docker compose file created in the previous post.</blockquote><p>I have added this in a separate if condition so that we won’t get any errors if we try to run our server without docker.</p><p>3. Now, go to the index.js file and add const logger = require(&#39;./logger&#39;); just below the express import line. Now, go to the app.listen at the end of the file and replace the console.log line with logger.info(`Server is running on port: ${port})`; . Finally it should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec8cd8557116e06c75f7c2266f2ff7e0/href">https://medium.com/media/ec8cd8557116e06c75f7c2266f2ff7e0/href</a></iframe><p>Additionally, you can replace line 34 with logger.error and and add more logger calls in the file.</p><p>4. Run $ docker-compose build to rebuild our web container</p><p>5. Run $ docker-compose run to verify our changes are working or not.</p><blockquote>Whenever we make a change to our container, we need to rebuild it with docker as docker stores our previous built containers and uses them again we run the docker-compose run command.</blockquote><p>Finally, you should see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlVHoWkC3XDy8lMNfvlCkg.png" /></figure><p>on your terminal.</p><p>Open docker desktop and select ‘volumes’ from upper left side. Select the volume with the name “&lt;name-of-your-server&gt;-logs-volume”. For example for me it is, application-monitoring-with-nodejs_logs-volume.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKmIrZmraYyMyLByn7pP4w.png" /></figure><p>Click on it and select data to see your server.log file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-aLpkehbPZ7l3BUP-AWPiQ.png" /></figure><h3>Setting up Grafana Cloud</h3><ol><li>Go to <a href="https://grafana.com/">https://grafana.com/</a> and select ‘Sign In’ at top right corner.</li><li>Select the create free account option at the bottom.</li><li>Create a new account by entering your id password or with google, github or any of the existing options. For me, I will be using the google option.</li><li>You will be asked for Team URL and Deployment region, leave them at default values and select finish setup.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ka0iHkIVffyzb0kpExwDKA.png" /></figure><p>Within a couple of minutes, your grafana instance will be read and you will be greeted with the following screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dX3wQfD2HG6HuZEbVgtI4Q.png" /></figure><p>5. Select button highlighted in the above picture and select stack as shown in the bottom picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UnlXGJ4ksLqiRZ-Zkg6lwg.png" /></figure><p>6. Click on send logs under Loki</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BMruU2SpMeKsHadSTgKHuA.png" /></figure><p>7. Click on generate now to generate a token</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F39-s3ZA8Vz8VaVWVb8iYw.png" /></figure><p>8. Fill a name for your API and select the role as MetricsPublisher [IMPORTANT] and click create API key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZuotEsmpkGFprUAegWNgQ.png" /></figure><p>9. Copy the API key shown on the next screen.</p><p>10. Scroll down on the page and under the “From a standalone host” section you will see a config file. Copy the URL under client from this file. This will be used to configure promtail later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBTaidHohHqB9NAJ7treOA.png" /></figure><h3>Setting up promtail</h3><ol><li>Create a promtail-config.yml file in the same folder as the docker-compose file. This file will be used to tell promtail from where to scrape the logs and where to upload it. Copy the below code in the file. DON’T FORGET TO REPLACE THE URL AND READ THE COMMENTS.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bebc1ab3d36dad36dc0ec2b05c450efa/href">https://medium.com/media/bebc1ab3d36dad36dc0ec2b05c450efa/href</a></iframe><p>2. Adding a promtail container to our docker-compose. Go to docker compose and in services define another container for promtail as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/752d5a9931ce79f40b8d95827ad2e764/href">https://medium.com/media/752d5a9931ce79f40b8d95827ad2e764/href</a></iframe><p>We will be using the promtail image provided by docker-hub and grafana. I have commented out lines to use environment variables. If you are using env variables in your config file then this is where you define them.</p><p>Focus in the volumes, there are two specified volumes. First is the logs volume where we is storing log files and since promtail has to ship them it too needs to access the same volume. Next is the config file for promtail which we load in the next step, with the command. NOTE: If you are using env variables, you need to pass “-config.expand-env=true” with the command.</p><p>And we are done. Just run docker-compose run to start the containers and let’s check our logs in grafana.</p><h3>Finishing Up</h3><p>Go to your stack (where you accessed send logs to loki in step 6 of setting up grafana cloud) and click on launch under Grafana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BM8DdU-HZIji5lBCq3KS1Q.png" /></figure><ol><li>From the left panel select Explore</li><li>Under sources select the loki source</li><li>Under labels, select file name as the name of your logs file</li><li>Run query from top right corner</li></ol><p>Reference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BxaYwryZElwY5f6ICBgTxw.png" /></figure><p>Now scroll down and you can see your logs.</p><blockquote>Note: You may see some extra lines in the logs, these are from previous runs of server after the logger was created as promtail scrapes the file from the beginning.</blockquote><p>You can find the whole code at <a href="https://github.com/garvit170/Application-Monitoring-with-NodeJs/tree/12791036bb7bbc8b2154324216268b0446cb79af">https://github.com/garvit170/Application-Monitoring-with-NodeJs/tree/12791036bb7bbc8b2154324216268b0446cb79af</a></p><p>Next Post: <a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-3-b8cba6210535">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-3-b8cba6210535</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71432ac1ec6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Application Monitoring with NodeJs , prometheus, Winston, Open telemetry and Grafana cloud]]></title>
            <link>https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-e2fddcb7698d?source=rss-523f4e7f1069------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2fddcb7698d</guid>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[monitoring-software]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <dc:creator><![CDATA[Garvitgulati]]></dc:creator>
            <pubDate>Mon, 10 Oct 2022 13:28:40 GMT</pubDate>
            <atom:updated>2022-10-26T18:15:08.771Z</atom:updated>
            <content:encoded><![CDATA[<h3>Application Monitoring with NodeJs , prometheus, Winston, Open telemetry and Grafana cloud</h3><p>Hello everyone, I recently had a chance to set up an application monitoring system for an organisation from scratch and felt there was a need for an updated resource which explains the concept from theory to implementation. This will be a series of posts where we will be covering setting up the following monitoring systems:</p><ol><li>Logs Collection [Winston + Promtail+ Grafana Loki] [<a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-2-71432ac1ec6b">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-2-71432ac1ec6b</a>]</li><li>Metrics Collection [Prometheus + Grafana Dashboards] [<a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-3-b8cba6210535">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-3-b8cba6210535</a>]</li><li>Traces Collection [Open telemetry + Grafana Dashboards] [<a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-4-4e4b34d814cc">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-4-4e4b34d814cc</a>]</li></ol><p>Don’t worry if it’s too many terms, we will take everything one by one.</p><p>So let’s get started.</p><h3>What is an Application Monitoring System?</h3><p>Application monitoring system helps to understand when our application system is not working and if it’s not working what is going wrong. It helps us collect insights on to how our system is working.</p><p>It is often referred to as observability of an application. When people talk about observability, it’s common to hear them refer to the three pillars of observability: metrics, logs, and traces. While not magically making a system more observable, paired in the right way, these three make up a somewhat complete stack of techniques for inspecting what’s going on inside a system.</p><p>Let us understand it’s importance with an example.</p><h3>Why is it important?</h3><p>Suppose you have an application deployed on a cloud server. Suddenly you receive a complain that your server is down or people are experiencing delayed responses. You realise that the server is overloaded and need optimisation but how do you find which api or function is the cause of the problem? How do you figure out which API/route receives the most traffic on your server? You can download the log files from the server but wouldn’t it be better if you had a dashboard storing all the logs at one place which could be easily queried?</p><p>This is where an application monitoring system comes handy. It shows all the logs, metrics (total number of requests on route, response length, node js heap memory, event loop etc.), traces ( which function called which function and how much time it took for execution).</p><p>This is what will be setting up in these posts one by one.</p><p>But before we begin monitoring an application, we need to create an application. In this post, we will be covering setting up the basic app and begin monitoring from next post.</p><h3>Prerequisites</h3><p>As we will be using a lot of different services together, it’s better to use docker to keep everything simple and I would advice you to do the same.</p><p>Don’t worry if you haven’t used docker before. This was even my first time with docker but it’s really simple and makes your life really simple.</p><p><strong>Why Docker?</strong></p><p>Suppose you have a table and a lot of stuff on it, ball, pen, vase, pictures etc. Now you have to move everything from one table to another. It’s difficult to do it one by one. Wouldn’t it be easier if we had a container? That is exactly how docker will help us. We will be using a variety of services for this: prom tail, prometheus, open telemetry and our node js application.</p><p>Installing these together, running each of them can be tedious hence we will be using docker for all this.</p><p>You can refer, <a href="https://docs.docker.com/get-started/">https://docs.docker.com/get-started/</a>, for basic introduction.</p><p><strong>VS Code</strong></p><p>I will be using VS code as it offers a terminal alongside the code but you can use any code editor you prefer.</p><h3>Setting up our sample NodeJs server</h3><p>We will be using express for setting up our server.</p><ol><li>Open your terminal and write $ mkdir Sample-Express-Server.Then use $ mkdir Sample-Express-Server to change the current work directory to the new folder</li><li>Run $ npm init to initialise a npm project. Input all the details or just press Enter to skip the fields. In the it should look something like this:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uHqwf2dxTnPnp4hQYcWTg.png" /></figure><p>3. After that run $npm install express</p><p>4. Open the folder in VS code or any other editor of your choice</p><p>5. Create an index.js file and paste the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/532c44df960657ccde69e533cefd16c0/href">https://medium.com/media/532c44df960657ccde69e533cefd16c0/href</a></iframe><p>The above code creates an express server on port 4500 with the following routes:</p><p>GET /: Details of responses on all routes</p><p>GET /hello: returns json “{hello:world}”</p><p>GET /slow: Slow request which responds between 3–5 s with ‘Slow url accessed!’</p><p>POST /bye: responds with “POST Request: + post data”</p><p>6. Run $ node index.js in terminal to start the server and verify everything is running<br>Terminal Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*FX51ViZfPd3oS0bBt2L8PQ.png" /></figure><p>Open <a href="http://localhost:4500/">http://localhost:4500/</a> in browser to see the response.</p><h3>Setting up docker</h3><ol><li>Docker ignore file: To tell docker what to ignore. It is similar to git ignore file. Create a file titled &#39;.dockerignore&#39; and write node_modules in it.</li><li>Build file for our server: Create a file named &#39;Dockerfile&#39; and paste the following code:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ffc282d87dd39049cb2dccede028fdd/href">https://medium.com/media/9ffc282d87dd39049cb2dccede028fdd/href</a></iframe><p>The Dockerfile specifies how to buid our server. First line specifies a node version to be used. Next we create a working directory where we copy our package.json file and install all the packages (Since docker ignores our node_modules folder as specified). Next we copy all the files from the directory where the build file is located to the docker working directory</p><p>I have commented out line 11 for those who want to specify port from the environment. If you are using an env file you can configure it later with docker-compose.</p><p>Next we expose the port 4500 of the container for external access to our server and lastly we specify the command to run our server.</p><p>Voila! we have created our first container which run our server.</p><p>We will be using docker compose to run this container but we can run this individual container as well. You can follow: <a href="https://docs.docker.com/get-started/02_our_app/">https://docs.docker.com/get-started/02_our_app/</a> for building and running containers seperately and learn more about them.</p><p>Now, let’s write a docker compose file which will help us multiple containers together.</p><h3>Docker-Compose</h3><p>The docker compose file helps us to define and run multiple containers together. For now, we would define only one container that is our express server but as we set up more services we will have multiple containers in our compose file.</p><ol><li>Create a new file named docker-compose.yml and paste the following code:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51d903a95d6d0bc5b3e746d52f3b1beb/href">https://medium.com/media/51d903a95d6d0bc5b3e746d52f3b1beb/href</a></iframe><p>The above file specified docker-compose version and a network for our app.Next, in services, it defines our container. I have attached a logs volume to our container, this will be used to store the log files our server generates in the next post. In ports, we specify which container port to map with which machine port. We are mapping container’s port 4500 with our machine’s 4500 port.</p><p>I have commented out lines for adding environment variables and file as I don’t have any here but if anyone wants to do so they can make the changes as per their use case.</p><p>Run $ docker-compose up in your terminal to run your container. For the first time, it may take some time to build (took 2 minutes for me). When it completes and your server runs, you will see application-monitoring-with-“nodejs-web-1 | Server is running on port: 4500” displayed. That’s when you know your server has started.</p><p>Open <a href="http://localhost:4500/">http://localhost:4500/</a> in browser to see the response.</p><p>Complete code for this blog can be found at: <a href="https://github.com/garvit170/Application-Monitoring-with-NodeJs/tree/ffe9e9cb532de10a10c16962daf98f781e84cc6b">https://github.com/garvit170/Application-Monitoring-with-NodeJs/tree/ffe9e9cb532de10a10c16962daf98f781e84cc6b</a></p><p>In the next post we will set up logging for this app.</p><p>Next Post: <a href="https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-2-71432ac1ec6b">https://medium.com/@garvitgulati47/application-monitoring-with-nodejs-prometheus-winston-open-telemetry-and-grafana-cloud-2-71432ac1ec6b</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2fddcb7698d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>