I am using 'OpenTelemetry.Contrib.Preview' package to attach ILogger standalone logs as Activity Events (aka Trace events) to co-relate the logs with trace & show at a single place like Jaeger. As part of the documentation if we want to attach the logs we need to call 'AttachLogsToActivityEvent' along with setting 'IncludeFormattedMessage' to true during the log setup at startup.cs. While I see the logs are successfully being attached to the activity but only the default 3 properties CategoryName, LogLevel & EventId are being added and the actual 'FormattedMessage' is not getting logged even though I have it enabled. Searched in their github repo where I found this below issue, but the same is not working here: https://github.com/open-telemetry/opentelemetry-dotnet-contrib/issues/134
Any idea what's missing?
csproj file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0-*" />
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="7.0.0" />
<PackageReference Include="OpenTelemetry.Contrib.Preview" Version="1.0.0-beta2" />
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.4.0-rc.1" />
<PackageReference Include="OpenTelemetry.Exporter.Jaeger" Version="1.4.0-rc.1" />
<PackageReference Include="OpenTelemetry.Exporter.Prometheus.AspNetCore" Version="1.4.0-rc.1" />
<PackageReference Include="OpenTelemetry.Exporter.Prometheus.HttpListener" Version="1.4.0-rc.1" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.4.0-rc.1" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol.Logs" Version="1.4.0-rc.1" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.4.0-rc.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.0.0-rc9.10" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.0.0-rc9.10" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.1.0-beta.2" />
</ItemGroup>
</Project>
Program.cs file (there are bunch of lines for swagger/versioning testing)
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenTelemetry;
using OpenTelemetry.Exporter;
using OpenTelemetry.Instrumentation.AspNetCore;
using OpenTelemetry.Logs;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using System;
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
services.AddProblemDetails();
services.AddEndpointsApiExplorer();
services.AddApiVersioning(options => options.ReportApiVersions = true)
.AddApiExplorer(
options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
})
.EnableApiVersionBinding();
services.AddSwaggerGen();
builder.Services.Configure<AspNetCoreInstrumentationOptions>(options => options.RecordException = true);
var resource = ResourceBuilder.CreateDefault().AddService("MyService");
builder.Services
.AddOpenTelemetry()
.ConfigureResource(ConfigureResource)
.WithTracing(o =>
{
o.SetSampler(new TraceIdRatioBasedSampler(1.0))
.AddSource("MyService")
.AddAspNetCoreInstrumentation(option => option.RecordException = true)
.AddHttpClientInstrumentation();
o.AddConsoleExporter(o => o.Targets = ConsoleExporterOutputTargets.Console);
}).StartWithHost();
builder.Logging.ClearProviders();
builder.Logging.Configure(o => o.ActivityTrackingOptions = ActivityTrackingOptions.SpanId | ActivityTrackingOptions.TraceId | ActivityTrackingOptions.ParentId);
builder.Logging.AddFilter<OpenTelemetryLoggerProvider>("*", LogLevel.Information);
builder.Logging
.AddOpenTelemetry(loggerOptions =>
{
loggerOptions.SetResourceBuilder(resource);
loggerOptions.IncludeFormattedMessage = true;
loggerOptions.IncludeScopes = true;
loggerOptions.ParseStateValues = true;
loggerOptions.AddConsoleExporter();
loggerOptions.AttachLogsToActivityEvent();
});
var app = builder.Build();
var common = app.NewVersionedApi("Common");
var commonV1 = common.MapGroup("/api/v{version:apiVersion}/common").HasApiVersion(1.0);
commonV1.MapGet("/", (ILogger<Program> logger) =>
{
logger.LogInformation("Calling hello world api!");
return Results.Ok("Hello World common v1!");
});
app.UseSwagger();
app.UseSwaggerUI(
options =>
{
var descriptions = app.DescribeApiVersions();
foreach (var description in descriptions)
{
var url = $"/swagger/{description.GroupName}/swagger.json";
var name = description.GroupName.ToUpperInvariant();
options.SwaggerEndpoint(url, name);
}
});
app.Run();
static void ConfigureResource(ResourceBuilder r) => r.AddService(
serviceName: "MyService",
serviceVersion: "1.0.0",
serviceInstanceId: Environment.MachineName);
Once I run the above program & execute the endpoint, I see the activity is getting logged with the additional 'log' even that I added as part of the endpoint execution, but it doesn't include the actual 'FromattedMessage' property though, like an example below...
I have opened the same issue in github too: https://github.com/open-telemetry/opentelemetry-dotnet/issues/4052
If I go to Project->MyApp->Properties->Settings and enter Name like WhichApp of type string and enter the Scope as Application and Value of PCB. When I show the value in
my main form using MessageBox.Show(Properties.Settings.Default.WhichApp); I see a message box showing "PCB".
But if I try to set the property using MSBuild.exe -property:WhichApp=SUB when I view the property value I still see "PCB".
How can I call the MSBuild.exe compiler tool to set the property at build time?
I tried used External Tools in Visual Studio..
Title: Set Property
Command: C:\Program Files(x86)\Microsoft Visual Studio\2017\WDExpress\MSBuild\15.0\Bin\MSBuild.exe
Arguments: -property:WhichApp=SUB
Initial Directory: $(ProjectDir)
---- WHAT I'M TRY TO ACCOMPLISH IN LOAD() METHOD OF MAIN FORM ----
if (Properties.Settings.Default.PCAppConfig == "PCB")
{
// create new PCB form
// PCBForm.ShowDialog();
}
else if (Properties.Settings.Default.PCAppConfig == "SUB")
{
// create new SUB form
// SUBForm.ShowDialog();
}
--- In solution by jtijn, I tried this to add another property called VersionNum but fails... ---
<Target Name="BeforeBuild">
<PropertyGroup>
<!--Default value.-->
<PcAppConfig Condition="'$(PcAppConfig)' == ''">PCB</PcAppConfig>
<VersionNum Condition="'$(VersionNum)' == ''">1.0.0.66</VersionNum>
<!--The source code.-->
<TheSourceCode>internal static class PcAppConfig{ public static readonly string value = "$(PcAppConfig)"%3B%0A }internal static class VersionNum{ public static readonly string value = "$(VersionNum)"%3B</TheSourceCode>
</PropertyGroup>
<!--Get current source so we can only create it again when needed, to avoid being recompiled.-->
<ReadLinesFromFile File="PcAppConfig.cs" ContinueOnError="True">
<Output TaskParameter="Lines" ItemName="CurrentSourceCode" />
</ReadLinesFromFile>
<!--Write source, if needed.-->
<WriteLinesToFile File="PcAppConfig.cs" Overwrite="True" Lines="$(TheSourceCode)" Condition="'#(CurrentSourceCode)' != '$(TheSourceCode)'" />
</Target>
--- Doesn't compile when values are changed, Fails to create setup files ...
My arguments to MSBuild.exe
SelectApp.csproj.user /p:PcAppConfig=SUB /p:VersionNum=1.0.0.67
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Compile Update="Form1.cs">
<SubType>Form</SubType>
</Compile>
</ItemGroup>
<Target Name="BeforeBuild">
<PropertyGroup>
<!--Default value.-->
<PcAppConfig Condition="'$(PcAppConfig)' == ''">PCB</PcAppConfig>
<VersionNum Condition="'$(VersionNum)' == ''">1.0.0.66</VersionNum>
<!--The source code.-->
<TheSourceCode>internal static class PCAppConfig{ public static readonly string value = "$(PcAppConfig)"%3B }%0Ainternal static class VersionNum{ public static readonly string value = "$(VersionNum)"%3B }</TheSourceCode>
</PropertyGroup>
<!--Get current source so we can only create it again when needed, to avoid being recompiled.-->
<ReadLinesFromFile File="PcAppConfig.cs" ContinueOnError="True">
<Output TaskParameter="Lines" ItemName="CurrentSourceCode" />
</ReadLinesFromFile>
<!--Write source, if needed.-->
<WriteLinesToFile File="PcAppConfig.cs" Overwrite="True" Lines="$(TheSourceCode)" Condition="'#(CurrentSourceCode)' != '$(TheSourceCode)'" />
<ItemGroup>
<Compile Update="PcAppConfig.cs">
<SubType>Component</SubType>
</Compile>
</ItemGroup>
</Target>
<Target Name="AfterCompile">
<Exec Command=""$(ProgramFiles)\Microsoft Visual Studio\2019\Professional\Common7\IDE\devenv.com" C:\DummyApps\SelectApp\PCBSetup\PCBSetup.vdproj /build "Debug|AnyCPU""/>
</Target>
</Project>
You can have the project generate C# source code based on an msbuild property. This target goes at the end in the project file:
<Target Name="BeforeBuild">
<PropertyGroup>
<!--Default value.-->
<PcAppConfig Condition="'$(PcAppConfig)' == ''">PCB</PcAppConfig>
<!--The source code.-->
<TheSourceCode>internal static class PcAppConfig{ public static readonly string value = "$(PcAppConfig)"%3B }</TheSourceCode>
</PropertyGroup>
<!--Get current source so we can only create it again when needed, to avoid being recompiled.-->
<ReadLinesFromFile File="PcAppConfig.cs" ContinueOnError="True">
<Output TaskParameter="Lines" ItemName="CurrentSourceCode" />
</ReadLinesFromFile>
<!--Write source, if needed.-->
<WriteLinesToFile File="PcAppConfig.cs" Overwrite="True" Lines="$(TheSourceCode)" Condition="'#(CurrentSourceCode)' != '$(TheSourceCode)'" />
</Target>
The resulting source file needs to be added to your project, can do this in VS after building once or else add this line along with the other Compile items:
<Compile Include="PcAppConfig.cs" />
Now in your code you can just use PcAppConfig.value.
To change the value build like
msbuild my.csproj /p:PcAppConfig=SUB
I want to set Assembly Version of C# project in csproj file with a self generated task.
I want to set Assembly Version to:
Major Version -> Project version: for example 3
Minor Version -> 0
Build Number -> Year + Calendarweek
Revision -> Current day of week
My idea was the following code.
But currently it is not working.
Any ideas what I should change?
<UsingTask TaskName="DetectAssemblyVersion" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<Result ParameterType="System.String" Output="true" />
</ParameterGroup>
<Task>
<Code Type="Fragment" Language="cs">
<![CDATA[
string year = System.DateTime.Now.ToString("yy");
int dayOfWeek = (int) System.DateTime.Now.DayOfWeek;
System.Globalization.DateTimeFormatInfo dfi = System.Globalization.DateTimeFormatInfo.CurrentInfo;
System.Globalization.Calendar cal = dfi.Calendar;
string calendarWeek = cal.GetWeekOfYear(System.DateTime.Now, dfi.CalendarWeekRule,
dfi.FirstDayOfWeek).ToString();
Result = "3.0." + year + calendarWeek + "."+ dayOfWeek.ToString();
Log.LogMessage(MessageImportance.High, "detect of current version: " + Result);
]]>
</Code>
</Task>
</UsingTask>
<Target Name="TestBuild" AfterTargets="Build">
<DetectAssemblyVersion>
<Output PropertyName="AssemblyVersion" TaskParameter="Result" />
</DetectAssemblyVersion>
<Message Importance="high" Text="new version: $(AssemblyVersion)" />
</Target>
I am using the NuGet.targets file from NuGet to automatically download NuGet.exe and then restore the packets in my project.
This was working well, however at work we have a proxy and this method was failing due to a (407) Proxy Authentication Required Exception. I modified the targets file to use the proxy details and although this method works in an application it does not work in the MSBuild Task, the code is identical.
If I hardcode the proxy and my login details it works, when I build my solution NuGet.exe is downloaded and the packages are restored correctly. The problem only appears to be the authentication in the MSBuild task, I have absolutely no idea why. I have attached my modified code.
If anyone can help I'd appreciate it. Thanks
<UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<OutputFilename ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Reference Include="System.Core" />
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Using Namespace="System.Net" />
<Using Namespace="Microsoft.Build.Framework" />
<Using Namespace="Microsoft.Build.Utilities" />
<Code Type="Fragment" Language="cs">
<![CDATA[
try
{
OutputFilename = Path.GetFullPath(OutputFilename);
Log.LogMessage("Downloading latest version of NuGet.exe...");
using(WebClient webClient = new WebClient())
{
webClient.UseDefaultCredentials = true;
webClient.Proxy = WebRequest.GetSystemWebProxy();
webClient.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
webClient.DownloadFile("https://www.nuget.org/nuget.exe", OutputFilename);
return true;
}
}
catch (Exception ex)
{
Log.LogErrorFromException(ex);
return false;
}
]]>
</Code>
</Task>
</UsingTask>
Is there a simple way of taking the value of a property and then copy it to another property with certain characters replaced?
Say propA=This is a value. I want to replace all the spaces in it into underscores, resulting in propB=This_is_a_value.
Here is the solution without scripting and no external jars like ant-conrib:
The trick is to use ANT's resources:
There is one resource type called "propertyresource" which is like a source file, but provides an stream from the string value of this resource. So you can load it and use it in any task like "copy" that accepts files
There is also the task "loadresource" that can load any resource to a property (e.g., a file), but this one could also load our propertyresource. This task allows for filtering the input by applying some token transformations. Finally the following will do what you want:
<loadresource property="propB">
<propertyresource name="propA"/>
<filterchain>
<tokenfilter>
<filetokenizer/>
<replacestring from=" " to="_"/>
</tokenfilter>
</filterchain>
</loadresource>
This one will replace all " " in propA by "_" and place the result in propB. "filetokenizer" treats the whole input stream (our property) as one token and appies the string replacement on it.
You can do other fancy transformations using other tokenfilters: http://ant.apache.org/manual/Types/filterchain.html
Use the propertyregex task from Ant Contrib.
I think you want:
<propertyregex property="propB"
input="${propA}"
regexp=" "
replace="_"
global="true" />
Unfortunately the examples given aren't terribly clear, but it's worth trying that. You should also check what happens if there aren't any underscores - you may need to use the defaultValue option as well.
If ant-contrib isn't an option, here's a portable solution for Java 1.6 and later:
<property name="before" value="This is a value"/>
<script language="javascript">
var before = project.getProperty("before");
project.setProperty("after", before.replaceAll(" ", "_"));
</script>
<echo>after=${after}</echo>
In case you want a solution that does use Ant built-ins only, consider this:
<target name="replace-spaces">
<property name="propA" value="This is a value" />
<echo message="${propA}" file="some.tmp.file" />
<loadfile property="propB" srcFile="some.tmp.file">
<filterchain>
<tokenfilter>
<replaceregex pattern=" " replace="_" flags="g"/>
</tokenfilter>
</filterchain>
</loadfile>
<echo message="$${propB} = "${propB}"" />
</target>
Output is ${propB} = "This_is_a_value"
Use some external app like sed:
<exec executable="sed" inputstring="${wersja}" outputproperty="wersjaDot">
<arg value="s/_/./g"/>
</exec>
<echo>${wersjaDot}</echo>
If you run Windows get it googling for "gnuwin32 sed".
The command s/_/./g replaces every _ with .
This script goes well under windows. Under linux arg may need quoting.
Two possibilities :
via script task and builtin javascript engine (if using jdk >= 1.6)
<project>
<property name="propA" value="This is a value"/>
<script language="javascript">
project.setProperty('propB', project.getProperty('propA').
replace(" ", "_"));
</script>
<echo>$${propB} => ${propB}</echo>
</project>
or using Ant addon Flaka
<project xmlns:fl="antlib:it.haefelinger.flaka">
<property name="propA" value="This is a value"/>
<fl:let> propB := replace('${propA}', '_', ' ')</fl:let>
<echo>$${propB} => ${propB}</echo>
</project>
to overwrite exisiting property propA simply replace propB with propA
Here's a more generalized version of Uwe Schindler's answer:
You can use a macrodef to create a custom task.
<macrodef name="replaceproperty" taskname="#{taskname}">
<attribute name="src" />
<attribute name="dest" default="" />
<attribute name="replace" default="" />
<attribute name="with" default="" />
<sequential>
<loadresource property="#{dest}">
<propertyresource name="#{src}" />
<filterchain>
<tokenfilter>
<filetokenizer/>
<replacestring from="#{replace}" to="#{with}"/>
</tokenfilter>
</filterchain>
</loadresource>
</sequential>
</macrodef>
you can use this as follows:
<replaceproperty src="property1" dest="property2" replace=" " with="_"/>
this will be pretty useful if you are doing this multiple times
Adding an answer more complete example over a previous answer
<property name="propB_" value="${propA}"/>
<loadresource property="propB">
<propertyresource name="propB_" />
<filterchain>
<tokenfilter>
<replaceregex pattern="\." replace="/" flags="g"/>
</tokenfilter>
</filterchain>
</loadresource>
Just an FYI for answer Replacing characters in Ant property - if you are trying to use this inside of a maven execution, you can't reference maven variables directly. You will need something like this:
...
<target>
<property name="propATemp" value="${propA}"/>
<loadresource property="propB">
<propertyresource name="propATemp" />
...
Properties can't be changed but antContrib vars (http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html ) can.
Here is a macro to do a find/replace on a var:
<macrodef name="replaceVarText">
<attribute name="varName" />
<attribute name="from" />
<attribute name="to" />
<sequential>
<local name="replacedText"/>
<local name="textToReplace"/>
<local name="fromProp"/>
<local name="toProp"/>
<property name="textToReplace" value = "${#{varName}}"/>
<property name="fromProp" value = "#{from}"/>
<property name="toProp" value = "#{to}"/>
<script language="javascript">
project.setProperty("replacedText",project.getProperty("textToReplace").split(project.getProperty("fromProp")).join(project.getProperty("toProp")));
</script>
<ac:var name="#{varName}" value = "${replacedText}"/>
</sequential>
</macrodef>
Then call the macro like:
<ac:var name="updatedText" value="${oldText}"/>
<current:replaceVarText varName="updatedText" from="." to="_" />
<echo message="Updated Text will be ${updatedText}"/>
Code above uses javascript split then join, which is faster than regex. "local" properties are passed to JavaScript so no property leakage.
Or... You can also to try Your Own Task
JAVA CODE:
class CustomString extends Task{
private String type, string, before, after, returnValue;
public void execute() {
if (getType().equals("replace")) {
replace(getString(), getBefore(), getAfter());
}
}
private void replace(String str, String a, String b){
String results = str.replace(a, b);
Project project = getProject();
project.setProperty(getReturnValue(), results);
}
..all getter and setter..
ANT SCRIPT
...
<project name="ant-test" default="build">
<target name="build" depends="compile, run"/>
<target name="clean">
<delete dir="build" />
</target>
<target name="compile" depends="clean">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes" includeantruntime="true"/>
</target>
<target name="declare" depends="compile">
<taskdef name="string" classname="CustomString" classpath="build/classes" />
</target>
<!-- Replacing characters in Ant property -->
<target name="run" depends="declare">
<property name="propA" value="This is a value"/>
<echo message="propA=${propA}" />
<string type="replace" string="${propA}" before=" " after="_" returnvalue="propB"/>
<echo message="propB=${propB}" />
</target>
CONSOLE:
run:
[echo] propA=This is a value
[echo] propB=This_is_a_value