<?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 Mayur kale on Medium]]></title>
        <description><![CDATA[Stories by Mayur kale on Medium]]></description>
        <link>https://medium.com/@mayurkale22?source=rss-d8d2c4dbc3ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*b9byz1x-UGUcoJ7a</url>
            <title>Stories by Mayur kale on Medium</title>
            <link>https://medium.com/@mayurkale22?source=rss-d8d2c4dbc3ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:42:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mayurkale22/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[Cloud Spanner: Read Statistics]]></title>
            <link>https://medium.com/google-cloud/cloud-spanner-read-statistics-71693d718131?source=rss-d8d2c4dbc3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/71693d718131</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cloud-spanner]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Mayur kale]]></dc:creator>
            <pubDate>Wed, 15 Jul 2020 16:48:22 GMT</pubDate>
            <atom:updated>2020-07-15T18:02:31.294Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://cloud.google.com/spanner">Cloud Spanner</a> is Google’s fully managed scalable relational database service. We recently announced a new feature, Spanner read statistics, that lets you run SQL queries to retrieve read statistics for your database during one-, 10-, and 60-minute intervals. These read statistics allow you to see the most common and most resource-consuming reads (done through <a href="https://cloud.google.com/spanner/docs/reads">Spanner Read APIs</a>) executed on your database.</p><p>In this post, you’ll see how to use these read statistics to identify which reads are involved in high CPU usage.</p><h3>Read statistics</h3><p>Read statistics provide insight into how an application is using the database, and are useful when investigating performance issues. For example, you can check which read shapes are running against a database and how frequently they run to help explain the performance characteristics of these read shapes. You can use the read statistics for your database to identify read shapes that result in high CPU usage. At a high level, read statistics will help you to understand the behavior of read traffic going into a database in terms of resource usage.</p><p>Spanner provides built-in tables that store statistics about reads. You can retrieve statistics from these <em>SPANNER_SYS.READ_STATS*</em> tables using SQL statements. See <a href="https://cloud.google.com/spanner/docs/introspection/read-statistics">Read Statistics</a> in our official Spanner introspection documentation for more details.</p><blockquote><strong>Note:</strong> we’ll use the term “<strong>read shape</strong>” in this document to refer to the set of columns read in a read request. Read statistics track properties of these read shapes.</blockquote><h3>Aggregated read statistics</h3><p>Spanner captures aggregated read statistics in the following system tables:</p><ul><li><em>SPANNER_SYS.READ_STATS_TOTAL_MINUTE</em>: Read shape statistics aggregated across one-minute intervals.</li><li><em>SPANNER_SYS.READ_STATS_TOTAL_10MINUTE</em>: Read shape statistics aggregated across 10-minute intervals.</li><li><em>SPANNER_SYS.READ_STATS_TOTAL_HOUR</em>: Read shape statistics aggregated across 60-minute intervals.</li></ul><p>Each row in the above tables contains aggregated statistics of all reads executed over the database during the specific time interval. So, the above tables contain only one row for any given time interval.</p><h3>Top read statistics</h3><p>The following tables track the read shapes with the highest CPU usage during a specific time period:</p><ul><li><em>SPANNER_SYS.READ_STATS_TOP_MINUTE</em>: Reads during one-minute intervals.</li><li><em>SPANNER_SYS.READ_STATS_TOP_10MINUTE</em>: Reads during 10-minute intervals.</li><li><em>SPANNER_SYS.READ_STATS_TOP_HOUR</em>: Reads during 60-minute intervals.</li></ul><p>Statistics are collected on a best-effort basis. As a result, it is possible for statistics to be missed. If Spanner is unable to store statistics for all reads run during the interval in these tables, the system prioritizes reads with the highest CPU usage during the specified interval.</p><h3>Troubleshooting high CPU usage with read statistics</h3><p>Spanner read statistics come in handy in cases where you need to investigate high CPU usage on your Spanner database or when you are just trying to understand the CPU-heavy read shapes on your database. Inspection of read shapes that use significant amounts of database resources gives Spanner users a potential way to reduce operational costs and possibly improve general system latencies. Using the following steps, we’ll show you how to use read statistics to investigate high CPU usage in your database.</p><h3>Step 1: Selecting a time period to investigate</h3><p>Start your investigation by looking for a time when your application began to experience high CPU usage. For example, let’s say the issue started occurring around <em>5:20pm</em> on May 28, 2020.</p><h3>Step 2: Gathering read statistics for the selected time period</h3><p>Having selected a time period to start our investigation, we’ll look at statistics gathered on the <em>READ_STATS_TOTAL_10MINUTE</em> table around that time. The results of this query might give us clues about how CPU and other read statistics changed over that period of time. The following query returns the aggregated read statistics from <em>4:30 pm</em> to <em>7:30 pm</em> (inclusive).</p><pre>SELECT<br>  interval_end,<br>  ROUND(avg_cpu_seconds,4),<br>  execution_count,<br>  avg_locking_delay_seconds<br>FROM SPANNER_SYS.READ_STATS_TOTAL_10MINUTE<br>WHERE<br>  interval_end &gt;= &quot;2020-05-28T16:30:00&quot;<br>  AND interval_end &lt;= &quot;2020-05-28T19:30:00&quot;<br>ORDER BY interval_end;</pre><p>Let’s take the following data as an example of the result we get back from our query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X5BCkBD-GIhnyt6M" /></figure><p>Here we see that average CPU time, <em>avg_cpu_seconds</em>, is higher in the <strong>highlighted</strong> intervals. For instance, the <em>interval_end</em> with the value <strong>2020–05–28 19:20:00</strong> has a higher CPU time. Let’s choose that interval to investigate further in the next step.</p><h3>Step 3: Finding which read shapes are causing high CPU usage</h3><p>Digging a little deeper, we now query the <em>READ_STATS_TOP_10MINUTE</em> table for the interval that we picked based on the preceding step. The results of this query can help indicate which read shapes cause high CPU usage.</p><pre>SELECT<br>  read_columns,<br>  ROUND(avg_cpu_seconds,4),<br>  execution_count,<br>  avg_rows<br>FROM SPANNER_SYS.READ_STATS_TOP_10MINUTE<br>WHERE<br>  interval_end = &quot;2020-05-28T19:20:00&quot;<br>ORDER BY avg_cpu_seconds DESC LIMIT 3;</pre><p>The following data is an example of the result from the query, returning information about the top three read shapes ranked by <em>avg_cpu_seconds</em>. Note the use of <a href="https://cloud.google.com/spanner/docs/functions-and-operators#round">ROUND</a> in our query to restrict the output of <em>avg_cpu_seconds</em> to four decimal places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DTzxffu5wB2F_fWH" /></figure><p>One reason for high CPU usage might be that you start to execute a few read shapes more frequently (<em>execution_count</em>). Perhaps the average number of rows that the read returned has increased (<em>avg_rows</em>). If none of those properties of the read shape reveal anything interesting, you can examine other properties such as <em>avg_locking_delay_seconds</em>, <em>avg_client_wait_seconds</em> or <em>avg_bytes</em>.</p><h3>Step 4: Applying best practices to reduce high CPU usage</h3><p>When you have gone through the preceding steps, consider whether any of these best practices will help your situation.</p><ul><li>The number of times Spanner executed read shapes during the interval is a good example of a metric that needs a baseline to tell you if a measurement is reasonable or a sign of a problem. Having established a baseline for the metric, you’ll be able to detect and investigate the cause of any unexpected deviations from normal behavior.</li><li>When you notice a spike in CPU usage, check if it can be correlated with a similar sudden spike in user requests or application behavior. If so, it might not indicate a problem.</li><li>Try the following query to find the top read shapes ranked by the number of times Spanner executed for each read shape:</li></ul><pre>SELECT interval_end, read_columns, execution_count<br>FROM SPANNER_SYS.READ_STATS_TOP_MINUTE<br>ORDER BY execution_count DESC<br>LIMIT 10;</pre><ul><li>If you are looking for the lowest possible read latencies, especially when using multi-region instance configurations, use <a href="https://cloud.devsite.corp.google.com/spanner/docs/reads?db=andrewby#read_types">stale reads instead of strong reads</a> to reduce/remove the <em>AVG_LEADER_REFRESH_DELAY_SECONDS</em> component of read latency.</li><li>If you are only doing reads, and you can express your read using a <a href="https://cloud.devsite.corp.google.com/spanner/docs/reads?db=andrewby#single_read_methods">single read method</a>, you should use that single read method. Single reads do not lock, unlike read-write transactions, therefore you should use read-only transactions over more expensive read-write transactions when you are not writing data.</li></ul><p>In summary, Spanner read statistics provide greater observability and insight into your database behaviors in terms of read traffic. This is in addition to already existing <a href="https://cloud.google.com/spanner/docs/introspection/transaction-statistics">transaction statistics</a> and <a href="https://cloud.google.com/spanner/docs/introspection/query-statistics">query statistics</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71693d718131" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/cloud-spanner-read-statistics-71693d718131">Cloud Spanner: Read Statistics</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DML and Mutations - a tale of two data altering techniques in Cloud Spanner]]></title>
            <link>https://medium.com/google-cloud/dml-and-mutations-a-tale-of-two-data-altering-techniques-in-cloud-spanner-df13c49f2617?source=rss-d8d2c4dbc3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/df13c49f2617</guid>
            <category><![CDATA[cloud-spanner]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Mayur kale]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 08:27:49 GMT</pubDate>
            <atom:updated>2020-09-10T16:53:53.223Z</atom:updated>
            <content:encoded><![CDATA[<p>Data Manipulation Language (DML) and Mutations are two APIs in Cloud Spanner that you can use to modify data. You may find yourself asking, “<strong>Why two alternative APIs</strong>?” or “<strong>When should I choose one over the other?</strong>”. Let’s demystify each and explore their similarities and differences, so you can answer those questions.</p><p>The code samples in this post refer to a fictitious music industry database with two tables <strong>Singers</strong> and <strong>Albums</strong> with the following schema. <strong>Albums</strong> is an interleaved table of <strong>Singers</strong>, which stores the albums list of each Singer.</p><pre>CREATE TABLE <strong>Singers</strong> (<br>  SingerId   INT64 NOT NULL,<br>  FirstName  STRING(1024),<br>  LastName   STRING(1024),<br>  BirthDate  DATE,<br>  LastUpdated TIMESTAMP,<br>) PRIMARY KEY(SingerId);</pre><pre>CREATE TABLE <strong>Albums</strong> (<br>  SingerId         INT64 NOT NULL,<br>  AlbumId          INT64 NOT NULL,<br>  AlbumTitle       STRING(1024),<br>  MarketingBudget  INT64,<br>) PRIMARY KEY(SingerId, AlbumId),<br>  INTERLEAVE IN PARENT <strong>Singers</strong> ON DELETE CASCADE;</pre><h3><strong>DML</strong></h3><p>The Cloud Spanner DML enables you to INSERT, UPDATE, and DELETE data in Spanner tables. You can run DML statements using the <a href="https://cloud.google.com/spanner/docs/reference/libraries">client libraries</a>, the Google <a href="https://cloud.google.com/spanner/docs/quickstart-console#run_a_query">Cloud Console</a>, and the <a href="https://cloud.google.com/sdk/gcloud/reference/spanner#execute_sql_statements">gcloud</a> command-line tool.</p><p>Spanner offers two implementations of DML execution, each with different properties. At a high level, there is:</p><ul><li><strong>Standard DML</strong>: suitable for OLTP (<a href="https://en.wikipedia.org/wiki/Online_transaction_processing">Online Transaction Processing</a>) workloads. The following Java sample code creates a read-write transaction and calls <em>executeUpdate()</em> to insert 4 records into the <strong>Singers</strong> table. To see examples in other supported languages, see <a href="https://cloud.google.com/spanner/docs/dml-tasks#client-library-dml">Modifying data using DML</a> in our official Spanner documentation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rRBJqdoXO4LwzfY-rRG_w.png" /></figure><ul><li><strong>Partitioned DML</strong>: enables large-scale, database-wide operations with minimal impact on concurrent OLTP operations by partitioning the keyspace and running the statement over the partitions in separate, smaller scoped transactions. Partitioned DML is designed for bulk updates and deletes: 1) Periodic cleanup and garbage collection. Examples are deleting old rows or setting columns to NULL. 2) Backfilling new columns with default values. An example is using an UPDATE statement to set a new column’s value to False where it is currently NULL.</li></ul><h3><strong>Mutations</strong></h3><p>Besides DML, users can use <a href="https://cloud.google.com/spanner/docs/modify-mutation-api">Mutations</a> to write data to Cloud Spanner. A Mutation represents a sequence of inserts, updates, and deletes that Spanner applies atomically to different rows and tables in a Spanner database.</p><p>You write data using a Mutation object. A Mutation object is a container for mutation operations to update, delete and insert data. You can include operations that apply to different rows, or different tables, in a mutation. After you define one or more mutations that contain one or more writes, you must apply the mutation to commit the write(s). Each change is applied in the order in which they were added to the Mutation.</p><p>Here’s an example, again in Java, of inserting 4 rows into Singers using the Mutation API. For each row, we add an insert mutation and then call <em>write()</em> to execute the mutations. To see examples in other supported languages, see <a href="https://cloud.google.com/spanner/docs/modify-mutation-api#inserting_new_rows_in_a_table">Modifying data using mutations</a> in our official Spanner documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obt-_5Bjptdi1_cam6Rc4Q.png" /></figure><h3>Comparing DML and Mutations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmQiDL9LvTVcNqE_KsaDWw.png" /><figcaption>Here are the high level similarities and differences between DML and Mutations.</figcaption></figure><p>Let’s take a deeper look at the differences.</p><ul><li><strong>Read Your Writes</strong> (reading uncommitted results within an active transaction) semantics: changes you make using DML statements are visible to subsequent statements in the same transaction. This is different from using mutations, where changes are not visible in any reads (including reads done in the same transaction) until the transaction commits. This is because mutations in a transaction are buffered client-side (locally) and sent to the server as part of the commit operation. As a result, mutations in the commit request are not visible to SQL or DML statements within the same transaction.</li><li><strong>Upsert</strong>: DML does not support a native upsert, an operation that inserts rows into a database table if they do not already exist, or updates them if they do. However, there is an <a href="https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Mutation">insert_or_update</a> operation in the mutations world. Applications using DML can work around this limitation by reading the row first, and then using the appropriate DML statement.</li><li><strong>Constraint Checking</strong>: Spanner checks the constraints after every DML statement. This is different from using mutations, where Spanner buffers mutations in the client until commit and checks constraints at commit time. Evaluating the constraints after each statement allows Spanner to guarantee that the data that a DML statement returns is consistent with the schema.</li><li><strong>SQL Syntax</strong>: DML provides a conventional way to manipulate data, you can reuse SQL skills to alter the data using the DML API.</li></ul><h3>Avoid using DML and Mutations in the same transaction</h3><p>If a transaction contains both DML statements and mutations in the commit request, Spanner executes the DML statements before the mutations. To avoid having to account for the order of execution in your client library code, you should use either DML statements or the mutations in a single transaction, but not both.</p><p>Here is an example that illustrates potentially surprising behavior. The code inserts two rows into Albums using the Mutation API. The snippet, then calls <em>executeUpdate()</em> to update the newly inserted rows and calls <em>executeQuery()</em> to read updated albums.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KFOnl_reQLzGo88aGqwX6Q.png" /></figure><p>If you were to execute this code, you’d see <em>0 records updated</em>. This happens because the changes we made using Mutations are not visible to subsequent statements until the transaction commits. Ideally, we should have buffered writes only at the very end of the transaction.</p><h3>Summary</h3><p>As we’ve seen, DML and Mutations support similar data manipulation features. Choosing which approach to use will depend on whether some of the richer features such as “Read Your Writes”, “Upsert” or support for SQL syntax are important to your use case.</p><p>Links to learn more:</p><ul><li><a href="https://cloud.google.com/spanner">Cloud Spanner</a></li><li><a href="https://cloud.google.com/spanner/docs/dml-tasks">Inserting, updating, and deleting data using Data Manipulation Language</a></li><li><a href="https://cloud.google.com/spanner/docs/modify-mutation-api">Inserting, updating, and deleting data using mutations</a></li></ul><p>Thanks to <a href="https://medium.com/u/b35ed4d5cfe2">Andrew Byrne</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df13c49f2617" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/dml-and-mutations-a-tale-of-two-data-altering-techniques-in-cloud-spanner-df13c49f2617">DML and Mutations - a tale of two data altering techniques in Cloud Spanner</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Troubleshooting Cloud Spanner Applications with OpenCensus]]></title>
            <link>https://medium.com/google-cloud/troubleshooting-cloud-spanner-applications-with-opencensus-2cf424c4c590?source=rss-d8d2c4dbc3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf424c4c590</guid>
            <category><![CDATA[cloud-spanner]]></category>
            <category><![CDATA[opencensus]]></category>
            <category><![CDATA[stackdriver-monitoring]]></category>
            <dc:creator><![CDATA[Mayur kale]]></dc:creator>
            <pubDate>Mon, 02 Mar 2020 17:15:37 GMT</pubDate>
            <atom:updated>2020-03-02T17:15:37.550Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/528/0*mCXpMVO6x-_POSN0" /></figure><p>This tutorial shows how to configure client-side metrics recording in your Cloud Spanner workloads using OpenCensus. While Cloud Spanner surfaces a number of helpful server-side metrics, applications can realize the added benefits of collecting metrics emitted by the Cloud Spanner client library. For example, only client-side metrics include session and transaction related information. These Spanner + OpenCensus metrics will provide you with enough data to enable you to spot, and investigate the cause of any unusual deviations from normal behavior.</p><p>Before I dive into the details let me provide a brief introduction to OpenCensus.</p><p><a href="https://opencensus.io/">OpenCensus</a> provides libraries for C++, Java, Go, Python, Javascript, .Net, Ruby, and PHP that that capture distributed traces and metrics from applications, and send this telemetry to backends like Cloud Monitoring, Cloud Trace, Prometheus, Jaeger, Datadog, etc. More info and the user manual are available on <a href="https://opencensus.io/">opencensus.io</a>.</p><p><strong><em>** Important: OpenCensus is being replaced by OpenTelemetry (currently entering beta), but the migration should not require much change to use the API. Read more </em></strong><a href="https://medium.com/opentracing/a-roadmap-to-convergence-b074e5815289"><strong><em>here</em></strong></a><strong><em>. **</em></strong></p><h3>Before you begin</h3><ul><li>Make sure you’re using Java 8 or greater and <a href="https://maven.apache.org/install.html">Apache Maven</a>.</li><li>Our example will run on Google Cloud and emit metrics to Cloud Monitoring and Traces to Cloud Trace, however you can run your code anywhere and can use any exporter <a href="https://github.com/census-instrumentation/opencensus-service#exporters">that OpenCensus supports</a>.</li></ul><h3>Client-side metrics for investigating the use and abuse of the session pool</h3><p>These simple metrics should allow you to diagnose a range of different issues, from the effects of changing the min/max session configuration, to detecting session leaks.</p><blockquote><a href="https://cloud.google.com/spanner/docs/sessions">Sessions</a> are a central concept in the Cloud Spanner API. All Spanner reads and writes are performed through a session. A session can have only one active transaction at any time.</blockquote><p><strong>1. Tracking the number of max-allowed sessions, configurable by the user</strong></p><p><em>cloud.google.com/java/spanner/max_allowed_sessions</em><strong>: </strong>This shows the maximum number of sessions allowed. If the current number of sessions in the pool is less than this and they are all in use, then a new session will be created for any new operation. If the current number of <strong>in-use sessions</strong> are the same as this number and a new request comes, the pool can either block or fail. This metric is labeled by database name, instance name and library version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uVNi7920o-QqrfkQ" /><figcaption>Fig 1: Visualizing the max_allowed_sessions</figcaption></figure><p><strong>2.</strong> <strong>Tracking the number of max-in-use sessions</strong></p><p><em>cloud.google.com/java/spanner/max_in_use_sessions</em>: This returns the maximum number of sessions that have been in use during the last maintenance window interval, so as to provide an indication of the amount of activity currently in the database. It is specific to the database and instance name it runs in. A maintenance window is a set 10 minute interval. After a complete maintenance window has passed, the value is reset to zero (and then starts increasing again). The value is updated every time a session is checked out of the pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ISPTnz0KyY-I5U4A" /><figcaption>Fig 2: Visualizing the max_in_use_sessions</figcaption></figure><p><strong>3. Tracking the number of recently-in-use sessions</strong></p><p><em>cloud.google.com/java/spanner/in_use_sessions</em>: This metric allows users to see instance-level and database-level data for the total number of sessions in use (or checked out from the pool) at this very moment. With the help of this metric, we can tell if the number of in-use sessions increases for any reason or suddenly drops to zero. Depending on probe intervals and average transaction duration, this number might often be measured to be zero for a system under low load. E.g. if the system executes 1 transaction per second, the average transaction duration is 300ms and the value is probed once every 10 seconds, there’s a chance that you will often measure the value between two transactions and get a zero. On a system with higher load, measuring this value will give the user a better idea of the distribution of the transactions over time. If this value is relatively constant most of the time, but suddenly shows a spike that cannot be correlated with a similar sudden spike in user requests, it might be an indication of a concurrency problem somewhere (locks in the database, concurrency issues in the application itself etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N6B-mDzkkTj6wFMP" /><figcaption>Fig 3: Visualizing the number of max_in_use_sessions in_use_sessions max_allowed_sessions operations</figcaption></figure><p><strong>4. Tracking the number of requests to get session timeouts (cumulative)</strong></p><p><em>cloud.google.com/java/spanner/get_session_timeouts</em>: This gives you an indication of the total number of get session timed-out instead of being granted (the thread that requested the session is placed in a wait queue where it waits until a session is released into the pool by another thread) due to pool exhaustion since the server process started. Consider this value in combination with the value of currently<strong> </strong><strong>in_use_sessions</strong> to understand the load on the database. This metric is labeled by database name, instance name and library version. In such a situation, you should observe a value for currently<strong> </strong><strong>in_use_sessions</strong> that is equal to (or almost equal to) <strong>max_allowed_sessions</strong> all the time. While that is an indication that something is not well, it could also be that the application and the session pool are operating at their max, but without actually being exhausted.</p><p>Below are the steps to troubleshoot this problem:</p><ol><li>Check your application log for LeakedSessionExceptions that occur when you close your Spanner instance. (Closing a Spanner instance, will close the session pool, and closing the session pool will trigger these LeakedSessionExceptions for all sessions that have not been checked back into the session pool before closing the pool.)</li><li>If you have LeakedSessionExceptions: Investigate the stack trace of these and fix the code that is checking out the session, but not checking them back in, for example not closing all ResultSets or by not closing a read-only transaction.</li><li>If you do not have LeakedSessionExceptions: Increase SessionPool.maxSessions.</li></ol><p><strong>5.</strong> <strong>Tracking the number of acquired and released sessions</strong></p><p><em>cloud.google.com/java/spanner/num_acquired_sessions</em>: This metric allows users to see the total number of acquired sessions.</p><p><em>cloud.google.com/java/spanner/num_released_sessions</em>: This metric allows users to see the total number of released (destroyed) sessions.</p><p>Under ideal conditions, the number of acquired sessions should be equal to (or almost equal to) the released session count. If the difference between the two is steadily increasing, it is certainly an indication that there is a session leak. The metric is also an indication of the load on the system, so if you were to present it as a timeline, you would be able to recognize peak and low load moments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*w9R6wP56eqpolppZc9xfvQ.png" /><figcaption>Fig 4: Visualizing the number of acquired and released sessions operations</figcaption></figure><h3>To set up and enable Metrics, follow these steps:</h3><h4>Step 1 — Setting Up and Enabling Enhanced Metrics</h4><p>In order to capture client-side metrics and distributed traces from the Cloud Spanner client, we need to use OpenCensus <a href="https://github.com/census-instrumentation/opencensus-java/tree/master/contrib/observability_ready_util">Observability Ready Util</a> for Java. This package provides a convenient wrapper so that developers can use OpenCensus easily.</p><p>By default, OpenCensus Observability Ready Util does the following things:</p><ul><li>Enables basic RPC (is a single call against a gRPC service, either streaming or unary) views to surface below mentioned server-side metrics:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bca4931e5ececb397e43baf510977ad/href">https://medium.com/media/7bca4931e5ececb397e43baf510977ad/href</a></iframe><ul><li>Sets probabilistic sampling rate to 0.0001 (1 in 10,000)</li><li>Creates and registers <a href="https://github.com/census-instrumentation/opencensus-java/tree/master/exporters/trace/ocagent">OCAgent Trace Exporter</a> to collect traces</li><li>Creates and registers <a href="https://github.com/census-instrumentation/opencensus-java/tree/master/exporters/metrics/ocagent">OCAgent Metrics Exporter</a> to collect metrics</li></ul><p>If you are using Maven, add this to your pom.xml file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba7ee8a1b10e02d037729a391f22bdfa/href">https://medium.com/media/ba7ee8a1b10e02d037729a391f22bdfa/href</a></iframe><p>If you are using Gradle, add this to your dependencies</p><pre><strong>compile</strong> &#39;io.opencensus:opencensus-impl:0.25.0&#39;<br><strong>compile</strong> &#39;io.opencensus:opencensus-contrib-observability-ready-util:0.25.0&#39;</pre><p>At the start of your application, configure OpenCensus:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*BHq40ZkwtkjR0ASHJTCTBA.png" /></figure><p>The Cloud Spanner client supports <a href="https://opencensus.io/stats/">OpenCensus Metrics</a>, which gives insight into the client internals and aids in debugging/troubleshooting production issues. Metrics prefixed with cloud.google.com/java/spanner/ focus on operational level metrics. RPC level metrics can be gleaned from gRPC’s metrics, which are prefixed with grpc.io/client/.</p><h4>Step 2 — Deploy OpenCensus Agent</h4><p>The OpenCensus Agent is a component that can collect traces and metrics from processes instrumented by OpenCensus or other monitoring/tracing libraries (Jaeger, Prometheus, etc.), do aggregation and smart sampling, and export traces and metrics to one or more monitoring/tracing backends. This component is optional (metrics and traces can be exported directly from any OpenCensus library), but the agent makes it easier to choose an exporter without rebuilding and redeploying your application.</p><p>Here’s an agent configuration that exports metrics to Cloud Monitoring:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b6dfd72b4559de56e3210f964d34ee8/href">https://medium.com/media/6b6dfd72b4559de56e3210f964d34ee8/href</a></iframe><p>The oc-agent can be run directly from sources, binary, or a Docker image.</p><p>Cloning source: Open up a new shell to get the OpenCensus agent</p><pre>$ git clone <a href="https://github.com/census-instrumentation/opencensus-service.git">https://github.com/census-instrumentation/opencensus-service.git</a><br>$ cd opencensus-service</pre><p>Building it: $ make agent</p><p>which will place the binary in the bin folder in your current working directory.</p><p>Running it: $ ./bin/ocagent_darwin — config=/config.yaml</p><h4>Step 3 — View the captured metrics with Stackdriver Metrics Explorer</h4><p>After you have enabled Metrics for your spanner client, you can view the metrics using Stackdriver Metrics Exporter.</p><ol><li>Navigate to the <a href="https://app.google.stackdriver.com/metrics-explorer">Metrics Explorer</a>.</li><li>In the “Find” resource type and metric field, enter the following: <em>cloud.google.com/java/spanner/in_use_sessions</em></li><li>Select this metric from the list.</li><li>In the right pane, the count of in-use sessions.</li></ol><h4>Step 4 — Time to clean up</h4><p>Since this tutorial uses multiple GCP components, please be sure to delete the associated resources once you are done.</p><h4>Sample Java application</h4><p>Clone the source repository for this tutorial: $ git clone <a href="https://github.com/mayurkale22/spanner-oc.git">https://github.com/mayurkale22/spanner-oc.git</a></p><p>Update the Java application with some configuration specific to your project. Navigate to the folder containing the Java source: $ cd src/main/java/com/example/spanner</p><p>Configure the environment variable in the application code to use the Cloud Spanner instance and database.</p><p>To build the example: $ mvn clean package</p><p>Run the following Maven commands to build and run the program: $ mvn exec:java -Dexec.mainClass=com.example.spanner.App</p><p>Go to <a href="http://localhost:8080/spanner/">http://localhost:8080/spanner/</a>, and start sending read requests.</p><h3>To Conclude…</h3><p>OpenCensus’s integration with Cloud Spanner thrives on being able to detect any unusual deviation from the normal in one or more metrics. The number of recently in-use sessions is a good example of a metric that needs a baseline to tell you if a measurement is reasonable or a sign of a problem. Having established a baseline for the metric, you’ll be able to spot, and investigate the cause of any unexpected deviations from normal behavior.</p><p>I hope this simple getting started guide gets you up and running. Let us know in the comment section below if you find this helpful and any suggestions or questions you may have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf424c4c590" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/troubleshooting-cloud-spanner-applications-with-opencensus-2cf424c4c590">Troubleshooting Cloud Spanner Applications with OpenCensus</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracing Serverless (Cloud Run) Applications with OpenCensus]]></title>
            <link>https://medium.com/@mayurkale22/tracing-serverless-cloud-run-applications-with-opencensus-73dbb32de5b8?source=rss-d8d2c4dbc3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/73dbb32de5b8</guid>
            <category><![CDATA[opencensus]]></category>
            <dc:creator><![CDATA[Mayur kale]]></dc:creator>
            <pubDate>Wed, 19 Feb 2020 00:34:51 GMT</pubDate>
            <atom:updated>2020-02-19T00:36:37.098Z</atom:updated>
            <content:encoded><![CDATA[<p>TL;DR: This post illustrates a Cloud Run application instrumented with OpenCensus’s Node.js library and export traces to Stackdriver backend.</p><h3>Background</h3><p>In the age of microservices and serverless, adequate tracing and metrics are even more critical for debugging and monitoring your services. When working with Cloud Run, there’s an added layer of complexity due to execution model where the it dynamically manages the allocation and provisioning of servers. A serverless application runs in stateless compute containers that are event-triggered, ephemeral, and fully managed by Google.</p><p>This blog post will cover Node.js tracing on Google Cloud Run, but this can be extended to other languages (ex: Python, Go, etc.). Code, configuration files, commands, and detailed instructions are provided in this <a href="https://github.com/mayurkale22/wiki-app">repo</a>.</p><p>Below, I will go through the steps to show example Node.js application, deploy it on Cloud Run and collect/view the traces.</p><p>First, <a href="https://console.cloud.google.com/projectcreate">create a new project</a> in Google Cloud Console and copy your project ID to use throughout this post. Let’s get started!</p><p><strong>Code Walkthrough</strong></p><p>The code is based on the <a href="https://github.com/mayurkale22/wiki-app">Example</a> using express.js, which makes calls to the <a href="https://en.wikipedia.org/">https://en.wikipedia.org</a> API to fetch top five related wiki pages and display the result to the page. Here’s what you’ll see once you run the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/0*UEYK8YX_ec2CGONG" /></figure><pre>// Install dependencies</pre><pre>$ npm install</pre><pre>// Run the app</pre><pre>$ npm start</pre><p>Navigate to <a href="http://localhost:8080/wiki">http://localhost:8080/wiki</a></p><p><strong>Instrument The Application</strong></p><p>We will now start instrumenting our application by adding the necessary OpenCensus libraries as well as adding a few lines of code to start the traces and stackdriver exporter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aXAjHIbdXHabPRpn" /></figure><blockquote><strong>Important</strong>: It must be <strong>before</strong> any require or import statements for other packages.</blockquote><p><strong>Build the image</strong></p><p>Now, build your container image using Cloud Build, by running the following command from the directory containing the Dockerfile:</p><pre>$ gcloud builds submit — tag gcr.io/$PROJECT_ID/wiki-app</pre><p>Cloud Build is a service that executes your builds on GCP. It executes a series of build steps, where each build step is run in a Docker container to produce your application container (or other artifacts) and push it to Cloud Registry, all in one command.</p><p><strong>Running locally</strong></p><p>If you would like to run and test the application locally from Cloud Shell, you can start it using this standard docker command:</p><pre>$ docker run -d -p 8080:8080 gcr.io/$PROJECT_ID/wiki-app</pre><p><strong>Deploy to Cloud Run</strong></p><p>Deploying your containerized application to Cloud Run is done using the following command:</p><pre>$ gcloud run deploy wiki-app \ <br>  --image gcr.io/$PROJECT_ID/wiki-app \<br>  --platform managed \<br>  --region us-central1 \<br>  --allow-unauthenticated</pre><p>The <strong>--allow-unauthenticated</strong> deploy option enables you to reach the application without authentication.</p><p>The <strong>--platform</strong> managed deploy option means that we’re requesting the fully-managed environment.</p><p>Then wait a few moments until the deployment is complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X6I3NJ045IRxClKo" /></figure><p>Alright, so now our app is up and running on Cloud Run! Next up is to access the deployed app and view the data exported to Stackdriver backend.</p><p><strong>Generated Traces</strong></p><p>The next screenshot shows a trace exported to Stackdriver as a result of the wiki app example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HsoaVSb1BUKDrdXP" /></figure><p><strong>Use OpenCensus Agent Instead of direct exporter</strong></p><p>With serverless, there’s no location to place an agent. We will be using GKE (Google Kubernetes Engine) to host the agent.</p><p><strong>Deploying the app to GKE</strong></p><p>Change the project id in file <strong>k8s/oc-service.yaml</strong> with the sed command</p><pre>$ sed -i.bak “s/{{PROJECT-ID}}/$GOOGLE_CLOUD_PROJECT/” k8s/oc-service.yaml</pre><p>Deploy the OpenTelemetry collector to the Kubernetes cluster</p><pre>$ kubectl apply -f k8s/oc-service.yaml</pre><p>And un-comment below lines in the example code to use the OC agent exporter. Along with this you need to set up the host and port based on the agent deployment when creating the OcAgentExporter instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TQkb6a3WrrWUhqsA" /></figure><p><strong>Time to clean up</strong></p><p>While Cloud Run does not charge when the service is not in use, you might still be charged for storing the built container image.</p><p>You can either decide to delete your GCP project to avoid incurring charges, which will stop billing for all the resources used within that project, or simply delete your wiki-app image using this command:</p><pre>$ gcloud container images delete gcr.io/$PROJECT_ID/wiki-app</pre><p>To delete the Cloud Run service, use this command:</p><pre>$ gcloud run services delete wiki-app \<br>  --platform managed \<br>  --region us-central1</pre><blockquote><em>OpenCensus is being replaced by </em><strong><em>OpenTelemetry</em></strong><em>, but the migration should not require much change to use of the API. Read more </em><a href="https://medium.com/opentracing/a-roadmap-to-convergence-b074e5815289"><em>here</em></a><em>.</em></blockquote><p>I hope this simple getting started guide gets you up and running. Let us know in the comment section below if you find this helpful and any suggestions or questions you may have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73dbb32de5b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Export Dropwizard metrics to OpenCensus]]></title>
            <link>https://medium.com/@mayurkale22/export-dropwizard-metrics-to-opencensus-1e98851693f8?source=rss-d8d2c4dbc3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e98851693f8</guid>
            <category><![CDATA[dropwizard]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[instrumentation]]></category>
            <dc:creator><![CDATA[Mayur kale]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 03:00:28 GMT</pubDate>
            <atom:updated>2018-11-06T03:00:28.094Z</atom:updated>
            <content:encoded><![CDATA[<p>Dropwizard Metrics is a popular solution used by Java developers to capture JVM and application-level metrics from their services. In addition to distributed tracing, OpenCensus also captures application-level metrics from Java services, and interoperability between Dropwizard and OpenCensus has been one of our most asked for Java features. We have good news: OpenCensus now provides an easy way to export and migrate Dropwizard metrics to OpenCensus, and then on to your backend of choice.</p><p>Benefits of doing this include the ability to export metrics to a variety of different backends, and the addition of labels on captured time-series metrics.</p><blockquote>“This integration opens up interesting possibilities for existing Dropwizard users. Current users can continue using Dropwizard in addition to OpenCensus metrics. It also enables users to export Dropwizard metrics to backends that didn’t natively support them before, like Stackdriver Monitoring,” — Pritam Shah, Engineering Manager for the Census team at Google</blockquote><p>Before I dive into the migration details let me provide a brief introduction to OpenCensus.</p><h3>OpenCensus</h3><p><a href="https://opencensus.io/">OpenCensus</a> is a single distribution of libraries to provide observability with distributed tracing and monitoring for your systems. OpenCensus was started at Google, and has a growing and very active community behind it. Everyone in the community is working hard to make sure that your favorite frameworks, libraries and modules are automatically instrumented without you having to do anything. For example, OpenCensus libraries support the following languages:</p><p><a href="https://github.com/census-instrumentation/opencensus-java">Java</a> , <a href="https://github.com/census-instrumentation/opencensus-go">Go</a>, <a href="https://github.com/census-instrumentation/opencensus-python">Python</a>, <a href="https://github.com/census-instrumentation/opencensus-cpp">C++</a>, <a href="https://github.com/census-instrumentation/opencensus-node">Nodejs</a>, <a href="https://github.com/census-instrumentation/opencensus-erlang">Erlang</a>, <a href="https://github.com/census-instrumentation/opencensus-ruby">Ruby</a>, <a href="https://github.com/census-instrumentation/opencensus-php">PHP</a>, <a href="https://github.com/census-instrumentation/opencensus-csharp">C#</a></p><p>and includes automatic instrumentation for most popular web and RPC framework in each of these languages. OpenCensus allows you to collect metrics and traces, and then export them to a variety of backends such as Prometheus, Stackdriver Tracing and Monitoring, DataDog, Graphite, Zipkin, Jaeger, Microsoft Azure Application Insights, Instana, SignalFx, <a href="https://www.honeycomb.io/blog/a-new-way-to-get-traces-into-honeycomb-collaboration-with-opencensus/">Honeycomb</a> etc.</p><h4><strong>OpenCensus Stats</strong></h4><p>Stats/Metrics are very useful in determining the health of the overall application and the health of individual micro-services from various perspectives. For example, mean and 99th percentile latency of the request, the number of cache hit vs cache miss, etc. OpenCensus Stats provides a mechanism to collect these stats and aggregate them. It also allows tagging, which can be used to group and filter them.</p><h4><strong>OpenCensus Tracing</strong></h4><p>In a distributed system, it is important to know how a request flows from one service to another and how long it takes to perform a task in each service. OpenCensus Tracing provides a mechanism to collect data across multiple spans and later join these spans to form a single trace for a request.</p><p>More info and the user manual are available on <a href="https://opencensus.io/">opencensus.io</a>.</p><h3>Convert Dropwizard metrics to OpenCensus format</h3><p>This section describes how each of the Dropwizard metrics translate into OpenCensus metrics. There are five different ways of measuring metrics in the library. They are <strong>Counter</strong>, <strong>Gauge</strong>, <strong>Meter</strong>, <strong>Histogram</strong>, and <strong>Timer</strong>.</p><h4>Dropwizard Counters</h4><p>A counter is just a gauge for an AtomicLong instance. Given a Dropwizard Counter with name <em>cache_evictions</em>, the following values are reported:</p><pre>╔════════════╦═════════════════╦═══════════════════════════════════╗<br>║ Attributes ║ DropWizard      ║ OpenCensus                        ║<br>╠════════════╬═════════════════╬═══════════════════════════════════╣<br>║ Name       ║ <em>cache_evictions </em>║ codahale_cache_evictions_counter  ║<br>║ Description║ -               ║ Collected from Dropwizard         ║                                                                                                                                                               <br>║            ║                 ║ (metric=cache_evictions,          ║<br>║            ║                 ║ type=com.codahale.metrics.Counter)║<br>║ Type       ║ Counter         ║ GAUGE_INT64                       ║<br>║ Unit       ║ -               ║ 1                                 ║<br>╚════════════╩═════════════════╩═══════════════════════════════════╝</pre><p><strong>NOTE</strong>:<em> OpenCensus’s CUMULATIVE_INT64 type represent monotonically increasing values. Since Dropwizard Counter goes up/down, it makes sense to report them as OpenCensus GAUGE_INT64.</em></p><h4><strong>Dropwizard Gauges</strong></h4><p>A gauge is an instantaneous measurement of a value. Given a Dropwizard Gauge with name <em>line_requests</em>, the following values are reported:</p><pre>╔════════════╦═════════════════╦═══════════════════════════════════╗<br>║ Attributes ║ DropWizard      ║ OpenCensus                        ║<br>╠════════════╬═════════════════╬═══════════════════════════════════╣<br>║ Name       ║ <em>line_requests   </em>║ codahale_line_requests_gauge      ║<br>║ Description║ -               ║ Collected from Dropwizard         ║                                                                                                                                                        <br>║            ║                 ║ (metric=<em>line_requests</em>,            ║<br>║            ║                 ║ type=&lt;class_name&gt;)                ║<br>║ Type       ║ Gauge           ║ GAUGE_INT64 or GAUGE_DOUBLE       ║<br>║ Unit       ║ -               ║ 1                                 ║<br>╚════════════╩═════════════════╩═══════════════════════════════════╝</pre><p><strong>NOTE</strong>: <em>For simplicity, OpenCensus uses GAUGE_DOUBLE type for any Number and GAUGE_INT64 type for Boolean values.</em></p><h4>Dropwizard Meters</h4><p>A meter measures the rate of events over time. Given a Dropwizard Meter with name <em>get_requests</em>, the following values are reported:</p><pre>╔════════════╦═════════════════╦═══════════════════════════════════╗<br>║ Attributes ║ DropWizard      ║ OpenCensus                        ║<br>╠════════════╬═════════════════╬═══════════════════════════════════╣<br>║ Name       ║ <em>get_requests    </em>║ codahale_get_requests_meter       ║<br>║ Description║ -               ║ Collected from Dropwizard         ║                                                                                                                                                               <br>║            ║                 ║ (metric=get_requests,             ║<br>║            ║                 ║ type=com.codahale.metrics.Meter)  ║<br>║ Type       ║ Meter           ║ CUMULATIVE_INT64                  ║<br>║ Unit       ║ -               ║ 1                                 ║<br>╚════════════╩═════════════════╩═══════════════════════════════════╝</pre><h4>Dropwizard Histograms</h4><p>A histogram measures the statistical distribution of values in a stream of data. Given a Dropwizard Histogram with name <em>results</em>, the following values are reported:</p><pre>╔════════════╦═══════════════╦═════════════════════════════════════╗<br>║ Attributes ║ DropWizard    ║ OpenCensus                          ║<br>╠════════════╬═══════════════╬═════════════════════════════════════╣<br>║ Name       ║ <em>results       </em>║ codahale_results_histogram          ║<br>║ Description║ -             ║ Collected from Dropwizard           ║                                                                                                                                                               <br>║            ║               ║ (metric=<em>results</em>,                    ║<br>║            ║               ║ type=com.codahale.metrics.Histogram)║<br>║ Type       ║ Histogram     ║ SUMMARY                             ║<br>║ Unit       ║ -             ║ 1                                   ║<br>╚════════════╩═══════════════╩═════════════════════════════════════╝</pre><h4>Dropwizard Timers</h4><p>A timer measures both the rate that a particular piece of code is called and the distribution of its duration. Given a Dropwizard Timer with name <em>requests</em>, the following values are reported:</p><pre>╔════════════╦═══════════════╦═════════════════════════════════════╗<br>║ Attributes ║ DropWizard    ║ OpenCensus                          ║<br>╠════════════╬═══════════════╬═════════════════════════════════════╣<br>║ Name       ║ <em>results       </em>║ codahale_requests_timer             ║<br>║ Description║ -             ║ Collected from Dropwizard           ║                                                                                                                                                               <br>║            ║               ║ (metric=<em>results</em>,                    ║<br>║            ║               ║ type=com.codahale.metrics.Timer)    ║<br>║ Type       ║ Timer         ║ SUMMARY                             ║<br>║ Unit       ║ -             ║ 1                                   ║<br>╚════════════╩═══════════════╩═════════════════════════════════════╝</pre><h3>How it works…</h3><p>We will follow four steps to complete the work.</p><h4>Step 1: Prerequisites</h4><p>Assuming, you already have both the OpenCensus and Dropwizard client libraries setup and working inside your application.</p><h4>Step 2: Add the dependencies to your project</h4><p>If you’ve got a Maven application, you’ll need to add opencensus-contrib-dropwizard as a dependency.</p><pre>&lt;dependencies&gt;<br>    &lt;dependency&gt;<br>        &lt;groupId&gt;<strong>io.opencensus</strong>&lt;/groupId&gt;<br>        &lt;artifactId&gt;<strong>opencensus-contrib-dropwizard</strong>&lt;/artifactId&gt;                  <br>        &lt;version&gt;<strong>0.17.0</strong>&lt;/version&gt;<br>    &lt;/dependency&gt;<br>&lt;/dependencies&gt;</pre><p>And you can find its latest version <a href="https://mvnrepository.com/artifact/io.opencensus">here</a>.</p><p>For Gradle add to your dependencies:</p><pre>compile ‘io.opencensus:opencensus-dropwizard:0.17.0’</pre><h4>Step 3: <strong>And the following code</strong></h4><pre>import java.util.Collections;<br>import<strong> </strong>java.io.IOException;<br>import<strong> </strong>io.opencensus.exporter.stats.prometheus.PrometheusStatsCollector;<br>import<strong> </strong>io.prometheus.client.exporter.HTTPServer;</pre><pre>public class YourClass {<br>  // Create registry for Dropwizard metrics.<br>  static final com.codahale.metrics.MetricRegistry <br>    codahaleRegistry = new com.codahale.metrics.MetricRegistry();<br><br>  // Create a Dropwizard counter.<br>  static final com.codahale.metrics.Counter <br>     requests = codahaleRegistry.counter(&quot;requests&quot;);<br><br>  public static void main(String[] args) {<br><br>    // Increment the requests.<br>    requests.inc();<br><br>    // Hook the Dropwizard registry into the OpenCensus registry<br>    // via the DropWizardMetrics metric producer.<br>    <strong>io.opencensus.metrics.Metrics.getExportComponent().getMetricProducerManager().add(<br>          new io.opencensus.contrib.dropwizard.DropWizardMetrics(<br>            Collections.singletonList(codahaleRegistry)));</strong></pre><pre><em>setupOpenCensusAndPrometheusExporter</em>();</pre><pre>...<br>  }</pre><pre>private static void<strong> </strong>setupOpenCensusAndPrometheusExporter() throws<strong> </strong>IOException {<br>    <em>// Register the Prometheus exporter<br>    </em><strong>PrometheusStatsCollector.<em>createAndRegister</em>();</strong><br><br>    <em>// Run the server as a daemon on address &quot;localhost:8888&quot;<br>    </em>HTTPServer server = new<strong> </strong>HTTPServer(<strong>&quot;</strong>localhost<strong>&quot;</strong>, 8888, true);<br>}</pre><pre>}</pre><h4>Step 4: View data</h4><p>Using supported backends such as Prometheus, Stackdriver Monitoring or SignalFx. Here are few sample charts created out of data exported by OpenCensus using Prometheus exporter.</p><p><a href="http://localhost:9090/">http://localhost:9090</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2U_1dkOtR1LS72Cm9jEbA.png" /><figcaption>Prometheus “Graph”</figcaption></figure><p>Go to <a href="http://localhost:9090/graph">http://localhost:9090/graph</a> and, start typing “codahale”. Select “codahale_requests_counter”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kBcRKFkEaBaGekEUsC6bbg.png" /><figcaption>Prometheus “codahale_requests_counter”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dzkhdv6XDOAYLv9tycn2ZQ.png" /><figcaption>Prometheus “codahale_get_requests_duration_size_gauge”</figcaption></figure><h3>Conclusion</h3><p>With OpenCensus and a few lines of changes it’s now very easy and straightforward to export from Dropwizard to the OpenCensus Java library. Give it a try: download the <a href="https://github.com/census-instrumentation/opencensus-java/tree/master/contrib/dropwizard">sample code</a> and get started today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e98851693f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>